我是 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 轴标签时采用 x+width/2.0
?
并且,如何在房屋盗窃之前在图表的开头设置较小的宽度?条形通常从 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()
最佳答案
Multiple assignment, tuple/sequence packing/unpacking :
>>>
>>> data = [ ("House Theft", 57), ("House Fire", 48),
("Car Theft", 156), ( "Car Accident", 245)]
>>>
>>> for thing in data:
(s, num) = thing
print thing, '\t', s, '\t', num
('House Theft', 57) House Theft 57
('House Fire', 48) House Fire 48
('Car Theft', 156) Car Theft 156
('Car Accident', 245) Car Accident 245
>>>
<小时/>
>>> for (s, num) in data:
print s, '\t\t', num
House Theft 57
House Fire 48
Car Theft 156
Car Accident 245
>>>
<小时/>
plt.xticks(x + width/2.0, labels )
会将 x 轴上的刻度偏移宽度的一半。不知道为什么这样做,除了视觉效果。
>>> x = np.arange(1,11)
>>> x
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> width = .5
>>> x + width/2
array([ 1.25, 2.25, 3.25, 4.25, 5.25, 6.25, 7.25, 8.25, 9.25, 10.25])
>>>
关于python - 在Python中绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32425045/