大型数据组x轴的熊猫条形图

时间:2016-11-02 07:26:22

标签: python python-2.7 python-3.x pandas matplotlib

我在pandas数据框中有一个表,其中包含2列

+----------+------------+
|        id| orders     |
+----------+------------+
| 1        | 1100       |
| 2        | 22753      |
| 3        | 34         |
| 4        | 11         |
| 5        | 430        |
| 6        | 1175       |

| ...      | ..         | 
| 800      | 17         |
+----------+------------+

我想绘制一个条形图,我希望x轴条的范围为

1-100,100-200,200-300等,直到700-800,

和y轴的各个总订单

请帮助我,我正在使用

matplotlib.pyplot包。

我尝试运行此代码

fig = plt.figure(figsize=(17, 6)) # Create matplotlib figure
ax = fig.add_subplot(111) # Create matplotlib axes

width = 0.2

df.orders.plot(kind='bar', color='red', ax=ax, width=width, position=1)

ax.legend()
plt.show()

出现是错误的,将其视为订单 occurances is by mistake,consider it as orders

1 个答案:

答案 0 :(得分:0)

您可以创建一个新的DataFrame来保存要绘制的汇总信息。对于此示例,我使用随机生成的数据:

# Build example DataFrame
n_ids = 800
ids = []
ods = []
for i in range(1, n_ids + 1):
    ids.append(i)
    ods.append(random.randint(5, 20000))

df = pd.DataFrame({'id': ids, 'orders': ods})

此数据框与您的数据框具有相同的结构。使用chunk_size 100(按照您的要求),您可以轻松计算每个id所属的块(或)并聚合{{ 1}}使用orders

sum()

新的# Group by chunks chunk_size = 100 # Add new column 'chunk' to describe groups df['chunk'] = [int((i - 1) / chunk_size) + 1 for i in df['id']] # Group, aggregate and store as new DataFrame pdf = pd.DataFrame(df.groupby(['chunk'])['orders'].sum()) 名为DataFrame,如下所示:

pdf

现在,您可以像以前一样简单地绘制聚合值:

        orders
chunk         
1       937595
2       987138
3      1109390
4      1097058
5      1039206
6      1060363
7       999461
8      1086585

干杯。

相关问题