use*_*242 1 python matplotlib data-analysis
非常新手的问题:
我需要从元组列表中绘制条形图.第一个元素是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)]
Run Code Online (Sandbox Code Playgroud)
小智 10
如果你有一个元组列表,你可以尝试下面的代码来获得你想要的.
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()
Run Code Online (Sandbox Code Playgroud)
这将为您提供类似下图的情节,但是当您不使用时间序列时,在条形图上绘制趋势线是没有意义的.
参考文献: