繁体   English   中英

在 python 中绘制条形 plot 时,如何在 3 列的 pandas 数据框中将其堆叠为 2 列而不是为一列堆叠?

[英]While plotting bar plot in python, how can I make it stacked for 2 columns and not stacked for one column in a pandas data frame of 3 columns?

我有一个包含 4 列的数据框。 说第 1 列、第 2 列、第 3 列、第 4 列。 column1 是 column3 和 column4 的总和。 我想 plot 一个酒吧 plot 与 column3 和 column4 堆叠,但 column1 和 column2 作为单个非堆叠的。 我该如何做这种混合堆叠?

这是日期框架,例如:

Date    column1 column2 column3 column4
    2021-08-20  19  30  11  8
    2021-08-11  15  25  11  4
    2021-08-07  5   10  5   0
    2021-08-19  25  36  16  9
    2021-08-31  6   6   6   0

我希望它看起来像这样,除了 1 个堆叠条(列 3 和列 4)

在此处输入图像描述

我正在尝试这个:

ax = final_df[['Date', 'column1', 'column2']].plot(kind = 'bar', x = 'Date', stacked = False, rot = 90, figsize = (20,5))
ax = final_df[['Date', 'column3', 'column4']].plot(kind = 'bar', x = 'Date', stacked = True, rot = 90, figsize = (20,5))

但这显然给了我2个地块

您可以通过 matplotlib plot 计算每个柱的位置。

以下示例代码使用列表列表来指示哪些列 go 在一起。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from io import StringIO

df_str = '''    Date    column1 column2 column3 column4
    2021-08-20  19  30  11  8
    2021-08-11  15  25  11  4
    2021-08-07  5   10  5   0
    2021-08-19  25  36  16  9
    2021-08-31  6   6   6   0'''
final_df = pd.read_csv(StringIO(df_str), delim_whitespace=True)

columns_to_plot = ['column1', 'column2', ['column3', 'column4']]

fig, ax = plt.subplots(figsize=(20, 5))
bar_spots = len(columns_to_plot)
bar_width = 0.8 / bar_spots
pos = np.arange(len(final_df))
dodge_offsets = np.linspace(-bar_spots * bar_width / 2, bar_spots * bar_width / 2, bar_spots, endpoint=False)
for columns, offset in zip(columns_to_plot, dodge_offsets):
    bottom = 0
    for col in ([columns] if isinstance(columns, str) else columns):
        ax.bar(pos + offset, final_df[col], bottom=bottom, width=bar_width, align='edge', label=col)
        bottom += final_df[col]
ax.set_xticks(pos)
ax.set_xticklabels(final_df['Date'], rotation=0)
ax.legend()
plt.tight_layout()
plt.show()

条形图,一些列堆叠,其他没有

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM