如何在Python中绘制一个条形图来显示不同类型商店类型的总销售额?

2024-10-03 19:20:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集(不是下面的数据集,而是类似的数据集),我试图用Python绘制一个条形图,这样我就可以直观地看到由不同类型的“门店类型”产生的“总销售额”。在

╔══════════╦════════════════════╦═══════╗
║ Location ║    Outlet_Type     ║ Sales ║
╠══════════╬════════════════════╬═══════╣
║ Bandra   ║ Supermarket Type 1 ║   125 ║
║ Worli    ║ Supermarket Type 2 ║   150 ║
║ Wadala   ║ Supermarket Type 3 ║   100 ║
║ Chembur  ║ Supermarket Type 2 ║   100 ║
║ Kalina   ║ Supermarket Type 3 ║   110 ║
║ Dadar    ║ Supermarket Type 3 ║   115 ║
║ Korba    ║ Supermarket Type 2 ║   135 ║
║ Asavari  ║ Supermarket Type 1 ║   145 ║
╚══════════╩════════════════════╩═══════╝

从上面的数据来看,我的条形图上应该有

X轴:“超市类型1”、“超市类型2”和“超市类型3”
Y轴:不同类型门店的总销售额

所以

“超市类型1”的值为270
“超市类型2”的值为385
“超市类型3”的值为325

在SQL术语中,它类似于执行“groupby”,但在Python中,我不能这样做,而是暂时使用pivot表。在

^{pr2}$

Tags: 数据类型type绘制location直观条形图sales
2条回答

你真的很接近。只是在当前方法中缺少一个aggfunc,因此pivot_table不能求和:

import matplotlib.pyplot as plt

data.pivot_table(values = 'Sales', index = 'Outlet_Type', aggfunc='sum').plot(kind='bar')
plt.tight_layout()
plt.show()

enter image description here

按插座类型分组,并进行汇总和绘图:

import matplotlib.pyplot as plt
data.groupby('Outlet_Type').sum()['Sales'].plot.bar()
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()

enter image description here 请参阅matplotlib文档,了解如何增强图表。在

相关问题 更多 >