我有一個包含 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個情節
uj5u.com熱心網友回復:
您可以通過 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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364276.html
標籤:Python 熊猫 matplotlib 条形图 堆积条系列
