[英]How to group stacked barplots? (use same label for several stacked barplots)
我的數據結構如下。 我想要的是為每個人創建堆疊的條形圖,並且只顯示 x label 分組。 但是,在我的嘗試中,它為每個人重復組 label:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.DataFrame(
{'Group':["A","A","B","B","C","C","C","D"],
'Individual':["ind1","ind2","ind3","ind4","ind5","ind6","ind7","ind8"],
'Component1':list(np.random.random(8)),
'Component2':list(np.random.random(8)),
'Component3':list(np.random.random(8)),
'Component4':list(np.random.random(8))
})
df.plot(x="Group", y=["Component1","Component2","Component3","Component4"], kind="barh",
stacked=True, legend=None, width=1, xlabel="")
這是重復組 label 的堆疊條形圖的圖
這就是我想要它們的方式:
有小費嗎?
您可以通過np.where
計算組之間的界限。 附加 0 和數組長度來處理左右邊界。 這些可用於繪制水平線並使標簽居中:
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(
{'Group': ["A", "A", "B", "B", "C", "C", "C", "D"],
'Individual': ["ind1", "ind2", "ind3", "ind4", "ind5", "ind6", "ind7", "ind8"],
'Component1': list(np.random.random(8)),
'Component2': list(np.random.random(8)),
'Component3': list(np.random.random(8)),
'Component4': list(np.random.random(8))
})
ax = df.plot(x="Group", y=["Component1", "Component2", "Component3", "Component4"], kind="barh",
stacked=True, legend=None, width=1, xlabel="", color=plt.cm.Set3.colors)
a = df['Group'].values
bounds = np.concatenate([[0], np.where(a[:-1] != a[1:])[0] + 1, [len(a)]])
ax.set_yticklabels([])
for b in bounds - 0.5:
ax.axhline(b, -0.06, 1, color='navy', ls='--', clip_on=False)
for b0, b1, label in zip(bounds[:-1] - 0.5, bounds[1:] - 0.5, a[bounds[1:] - 1]):
ax.text(-0.03, (b0 + b1) / 2, label, ha='right', va='center', size=14, transform=ax.get_yaxis_transform())
for spine in ax.spines:
ax.spines[spine].set_visible(False) # hide the spines
ax.set_ylim(-0.5, len(a) - 0.5) # no empty space at top and bottom
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.