python 元组列表中的条形图

标签 python matplotlib data-analysis

非常新手的问题:

我需要从元组列表中绘制条形图。第一个元素是 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()

这将为您提供如下图所示的图,尽管当您不使用时间序列时,在条形图上绘制趋势线没有意义。

Bar plot of popularity_data

引用文献:

关于python 元组列表中的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925251/

相关文章:

python - 注册基于 Celery 类的任务

python - 如何使用matplotlib在同一窗口中绘制多个散点图?

python - 将网格从中心坐标重新采样到外部(即角)坐标

database - 统计Linux服务器上的文件夹和文件结构

python - 如何检索查询集对象中字段的值

python - 在Python中混合/叠加WAV音频文件

python - 使用 Python 的 Azure Blob 存储,创建容器但不列出它们?

python - 使用嵌套 Matplotlib Gridspec 的紧密布局时出错

python - 如何在python中删除数据框中数据列中的0

python - 如何将以天、小时、分钟和秒为单位的时间转换为仅以秒为单位