非常新手的问题:
我需要从元组列表中绘制条形图。第一个元素是 x 轴的名称(分类),第二个元素是浮点类型(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)]
最佳答案
如果您有元组列表,您可以尝试以下代码来获得您想要的。
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()
这将为您提供如下图所示的图,尽管当您不使用时间序列时,在条形图上绘制趋势线没有意义。
引用文献:
关于python 元组列表中的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925251/