[英]Group together bars and labels in python matplotlib barchart
我目前正在嘗試在Python 3.x中使用matplotlib創建分組和堆疊的條形圖。 我只能使堆疊的部分正常工作,而無法將它們分組。
#This is what my dataframe looks like
Product_set Opened s1 s2 s3 s4
0 Product 1 Mar-19 1 NaN 1 NaN
1 Product 1 May-19 5 89.0 210 19.0
2 Product 1 Jun-19 14 117.0 282 33.0
3 Product 1 Jul-19 12 114.0 219 27.0
4 Product 2 Apr-19 1 7.0 5 NaN
5 Product 2 May-19 10 94.0 102 6.0
6 Product 2 Jun-19 10 103.0 131 13.0
7 Product 2 Jul-19 8 82.0 98 7.0
8 Product 3 Apr-19 1 11.0 24 4.0
9 Product 3 May-19 35 157.0 318 32.0
10 Product 3 Jun-19 36 236.0 354 49.0
11 Product 3 Jul-19 31 189.0 264 30.0
12 Product 4 May-19 42 146.0 353 84.0
13 Product 4 Jun-19 61 218.0 478 103.0
14 Product 4 Jul-19 38 126.0 306 104.0
ax=data.plot.bar(stacked=True,figsize=(20,7),edgecolor="black")
ax.minorticks_on()
plt.xticks(rotation=360)
plt.xlabel('')
plt.ylabel('')
plt.title('')
ax.tick_params(axis='x', which='major', pad=30, size=0)
# Set minor X labels
pos = []
for bar in ax.patches:
pos.append(bar.get_x()+bar.get_width()/2.)
ax.set_xticks(pos,minor=True)
ax.set_xticklabels(data['Product_set'])
ax.set_xticklabels(data['Opened'],minor=True)
plt.show()
我想這樣做,因此它只顯示一次產品名稱,並且同一產品的條形之間沒有空格。
您可以使用類似的方法偽造數據標簽
ax.set_xticklabels(['','','Product 1','','','','Product 2','','','','Product 3','','','Product4',''])
要關閉空格,請在plot.bar語句中使用align='edge'
,並在產品之間添加一些值為0的欺騙條目。 由於日期和產品僅在標簽中,因此只需為欺騙條目添加另一個空字符串
編輯:更加動態
dataframe.plot.bar具有可以使用的x = [positions]參數。 您將需要創建一個帶有位置的數組,可能是諸如data.index+int(data.Product_set[-1])
類的數組,該數組會將您的產品編號添加到索引中,從而方便地在產品之間留出額外的空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.