【问题标题】:Pandas bar graph for huge data group x axis大数据组 x 轴的 Pandas 条形图
【发布时间】:2016-11-02 07:26:22
【问题描述】:

我在 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()

发生是错误的,将其视为订单

【问题讨论】:

  • df.plot(kind='bar', color='red', ax=ax, width=width, position=1)。你可以试试这个吗?
  • @Backtrack 我试过了,但是在 x 轴上我有从 1 到 800 的单独条,这是不合适的,我希望它在 1-100、100-200 等组中
  • 你应该创建一个新的dataframe,它有8行和相应的订单总和。
  • @jbndlr 先生,看到我也添加了图像,您能告诉我该怎么做吗?我以前的 df 有 8 行的新数据框
  • plt.xticks(np.arange(min(df.id), max(df.id)+100, 100.0))。像这样的东西

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


【解决方案1】:

您可以创建一个新的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})

此数据框的结构与您的相同。使用100chunk_size(如您所愿),您可以轻松计算每个id 所属的块(或),并使用sum() 聚合orders

# 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())

名为pdf 的新DataFrame 如下所示:

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

现在,您可以像之前尝试的那样简单地绘制聚合值:

# Plot aggregates
fig = plt.figure(figsize=(17, 6))
ax = fig.add_subplot(111)

width = 0.2

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

ax.legend()
plt.show()

干杯。

【讨论】:

    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多