我是Python编程新手。我正在学习Python。在python中绘制条形图
下面的代码帮我画了一张条形图。我想了解代码。 我看不惯线5,6,7和8即
N = len(data)
x = np.arange(1,N+1)
y = [num for (s, num) in data ]
labels = [ s for (s, num) in data ]
而且,我们为什么要采取x+width/2.0
,同时绘制x轴的标签? 而且,如何在房子盗窃之前在图表的开始处添加一个小宽度?酒吧通常以0开头。我不知道如何在第一个酒吧开始前带上一个小宽度。我试过了,但没有好转。
完整的程序如下。
import matplotlib.pyplot as plt
import numpy as np
data = [ ("House Theft", 57), ("House Fire", 48),
("Car Theft", 156), ("Car Accident", 245)]
N = len(data)
x = np.arange(1,N+1)
y = [num for (s, num) in data ]
labels = [ s for (s, num) in data ]
width = 0.35 #Use 1 to make it as a histogram
bar1 = plt.bar(x, y, width, color="y")
plt.ylabel('Frequency')
plt.xticks(x + width/2.0, labels)
plt.show()
'''data'''是一个列表 - ['''len'''](https://docs.python.org/3/library/functions.html#len)。 [''numpy'''](http://docs.scipy.org/doc/numpy/user/)('''np''')是一个库 - ['''np.arange''' ](http://docs.scipy.org/doc/numpy-1.6.0/reference/generated/numpy.arange.html)。第7行和第8行是[list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)。 – wwii
@wwii这行'num(s,num)in data'表示什么?我了解数据是范围。这些变量和数字表明什么?与字符串和数字有关?他们究竟想要在这里做什么? –
['''tuple''' unpacking](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)。解释型语言的一个好处是,您可以轻松地使用shell中的语言功能来尝试一些东西,看看它是如何工作的。 Python有一个相当不错的[教程](https://docs.python.org/3/tutorial/index.html)。 – wwii