# 在python中绘制条形图

xkcvk2511

N = len(data)
x = np.arange(1,N+1)
y = [num for (s, num) in data ]
labels = [ s for (s, num) in data ]

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 = [ ("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])
>>>

0 条评论