【问题标题】: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?在 python 中绘制条形图时,如何在 3 列的 pandas 数据框中将其堆叠为 2 列而不是为一列堆叠?
【发布时间】:2022-01-01 15:58:06
【问题描述】:

我有一个包含 4 列的数据框。说第 1 列、第 2 列、第 3 列、第 4 列。 column1 是 column3 和 column4 的总和。我想绘制一个柱状图,其中 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 个地块

【问题讨论】:

  • 但是仍然会有 2 个不同的组看起来堆叠?我怎样才能将它们合并为一个

标签: python pandas matplotlib bar-chart stackedbarseries


【解决方案1】:

您可以通过 matplotlib 绘图,计算每个条的位置。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多