非常新手的问题:
我需要从元组列表中绘制条形图。第一个元素是x轴的名称(分类),第二个元素是float类型(对于y轴)。我还想按降序排列条形图,并添加趋势线。以下是一些示例代码:
In [20]: popularity_data
Out[20]:
[('Unknown', 10.0),
(u'Drew E.', 240.0),
(u'Anthony P.', 240.0),
(u'Thomas H.', 220.0),
(u'Ranae J.', 150.0),
(u'Robert T.', 120.0),
(u'Li Yan M.', 80.0),
(u'Raph D.', 210.0)]
答案 0 :(得分:9)
如果你有一个元组列表,你可以尝试下面的代码来得到你想要的。
import numpy as np
import matplotlib.pyplot as plt
popularity_data = [('Unknown', 10.0),
(u'Drew E.', 240.0),
(u'Anthony P.', 240.0),
(u'Thomas H.', 220.0),
(u'Ranae J.', 150.0),
(u'Robert T.', 120.0),
(u'Li Yan M.', 80.0),
(u'Raph D.', 210.0)]
# sort in-place from highest to lowest
popularity_data.sort(key=lambda x: x[1], reverse=True)
# save the names and their respective scores separately
# reverse the tuples to go from most frequent to least frequent
people = zip(*popularity_data)[0]
score = zip(*popularity_data)[1]
x_pos = np.arange(len(people))
# calculate slope and intercept for the linear trend line
slope, intercept = np.polyfit(x_pos, score, 1)
trendline = intercept + (slope * x_pos)
plt.plot(x_pos, trendline, color='red', linestyle='--')
plt.bar(x_pos, score,align='center')
plt.xticks(x_pos, people)
plt.ylabel('Popularity Score')
plt.show()
这将为您提供类似下图的情节,但是当您不使用时间序列时,在条形图上绘制趋势线是没有意义的。
参考文献:
答案 1 :(得分:0)
你应该使用字典,它更容易使用。这会按降序显示条形码:
popularity_data = {
'Unknown': 10.0,
u'Drew E.': 240.0,
u'Anthony P.': 240.0,
u'Thomas H.': 220.0,
u'Ranae J.': 150.0,
u'Robert T.': 120.0,
u'Li Yan M.': 80.0,
u'Raph D.': 210.0
}
for y in reversed(sorted(popularity_data.values())):
k = popularity_data.keys()[popularity_data.values().index(y)]
print k + ':', y
del popularity_data[k]
您可以使用matplotlib添加趋势线,建议为Aleksander S
。
另外,如果您愿意,可以将它存储在元组列表中,就像您最初那样:
popularity_data = {
'Unknown': 10.0,
u'Drew E.': 240.0,
u'Anthony P.': 240.0,
u'Thomas H.': 220.0,
u'Ranae J.': 150.0,
u'Robert T.': 120.0,
u'Li Yan M.': 80.0,
u'Raph D.': 210.0
}
descending = []
for y in reversed(sorted(popularity_data.values())):
k = popularity_data.keys()[popularity_data.values().index(y)]
descending.append(tuple([k, y]))
del popularity_data[k]
print descending
答案 2 :(得分:-1)
您可以使用ASCII字符表示条形图,也可以查看matplotlib ...