我有兩個資料框:
df1=pd.DataFrame(10*np.random.rand(4,3),index=[2,3,4,5],columns=["I","J","K"])
df2=pd.DataFrame(10*np.random.rand(4,3),index=[1,2,3,4],columns=["I","J","K"])
創建條形圖后,我得到:

現在我想將它們合并成一個圖形,所以我嘗試了:
fig, ax = plt.subplots(sharex=True)
ax1 = df1.plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=1, colormap="bwr", ax=ax, alpha=0.7)
ax2 = df2.plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=0, colormap="BrBG", ax=ax, alpha=0.7)
plt.show()
但結果并不是我所期望的:

如您所見,我希望 x 軸具有值 1、2、3、4、5,并且圖形對應于它們的原始索引值。問題出在哪里,我該如何解決?
此外,如果可能的話,我需要自動設定新的軸值,因為我有許多這些資料框都具有不同的軸值,手動插入新的軸值需要很長時間。也許我可以.unique()在索引列中使用并以某種方式實作它?
uj5u.com熱心網友回復:
您可以將兩個資料幀重新索引到相同的索引:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df1 = pd.DataFrame(10 * np.random.rand(4, 3), index=[2, 3, 4, 5], columns=["I", "J", "K"])
df2 = pd.DataFrame(10 * np.random.rand(4, 3), index=[1, 2, 3, 4], columns=["I", "J", "K"])
fig, ax = plt.subplots()
combined_index = df1.index.union(df2.index)
df1.reindex(combined_index).plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=1,
colormap="bwr", alpha=0.7, ax=ax)
df2.reindex(combined_index).plot.bar(legend=True, rot=0, stacked=True, width=0.1, position=0,
colormap="BrBG", alpha=0.7, ax=ax)
plt.show()

Pandas 條形圖0,1,2,...使用資料框的索引創建分類 x-ticks(內部編號)。首先分配內部刻度位置,然后分配標簽。通過對兩個資料幀使用相同的索引,位置將重合。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/380624.html
標籤:Python 熊猫 matplotlib 条形图
