如何用三个轴绘制分组数据框?

问题描述 投票:0回答:1

我有一个包含三列的分组数据框:时间戳、类别和值。我已按时间戳对数据帧进行分组并将其用作索引。我想绘制彼此堆叠的类别值。

  TIMESTAMP        CATEGORY_1  count
0   2023-03-31        correct     30
1   2023-03-31    not correct     11
2   2023-03-31        no info      2
3   2023-04-30        correct     15
4   2023-04-30    not correct      8

  TIMESTAMP             CATEGORY_2  count
0   2023-03-31                okay     29
1   2023-03-31             no info     17
2   2023-03-31             too high     4


  TIMESTAMP       CATEGORY_3  count
0   2023-03-31                 okay      4
1   2023-03-31              no info      2
2   2023-03-31             positive      3
3   2023-03-31             negative      2

当我使用时

df.pivot_table(index='timestamp', columns='category1',
values='count', aggfunc='mean').plot(kind='bar', stacked=True) 

效果很好。这是一个类别(一个数据框)

我有三个不同的类别,具有三个不同的值,它们都共享相同的时间戳。我想将它们绘制在一个轴上,这样我就不必来回滚动来查看三个图。

fig, (ax1, ax2, ax3) = plt.subplots(1, 3)

ax1.bar(x=df.index, y='category1', data=df1, stacked=True) 
ax2.bar(x=df.index, y='category2', data=df2, stacked=True)
ax3.bar(x=df.index, y='category3', data=df3, stacked=True)`

它不起作用。遗憾的是我无法使用海运图书馆。

有什么建议吗?我看到了一些带有 for 循环的解决方案,如下所示如何创建具有三列和三行的三个数据框的堆叠条,但并不完全清楚两个变量对应于哪一列。

pandas matplotlib bar-chart subplot
1个回答
0
投票

以下是根据您提供的数据在单个图表上绘制堆叠条形的示例。我不确定这是否正是您想要的图,但下面的代码演示了创建堆积图的流程:

import pandas as pd
from matplotlib import pyplot as plt


df1 = pd.read_csv('cat1.csv')
df2 = pd.read_csv('cat2.csv')
df3 = pd.read_csv('cat3.csv')

fig, ax = plt.subplots()

# keep track of the previous colors and legend for figure
colors = {}
labels = {}

for i in range(1, 4):
    # load data
    df = pd.read_csv(f"cat{i}.csv").sort_values("count", ascending=False)
    # filter date for example
    df = df[df["TIMESTAMP"] == "2023-03-31"]
    # previous cumulative bar height for dataset
    prev = 0
    for _, row in df.iterrows():
        val = row['count']
        label = row[f'CATEGORY_{i}']
        color = colors.get(label, None)
        bars = ax.bar(i, val, bottom=prev, width=0.5, color=color)
        if color is None:
            bar = bars[0]
            colors[label] = bar.get_facecolor()
            labels[label] = bar
        prev += val

ax.set_xticks(range(1, 4))
ax.set_xlabel("Category")
ax.set_ylabel("Count")
ax.legend(labels.values(), labels.keys())

© www.soinside.com 2019 - 2024. All rights reserved.