![](/img/trans.png)
[英]Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?
[英]Defining xlabels with set() and changing bottom arg inside subplots_adjust() matplotlib will modify xlabels order
我有兩個要繪制的數據集:
lwm:
Client name,CTR,mean_diff
customeronewithverylongname,0.08355714285714286,-0.02935714285714286
customertwowithverylongname,0.028471428571428568,-0.001942857142857142
customerthree,0.014371428571428571,0.000700000000000001
customerfourwithverylongname,0.09971428571428573,0.0014285714285714457
customerfive,0.006799999999999999,0.0014999999999999987
customersixQuickSale,0.0396,0.005075000000000003
customerseven,0.16254285714285713,0.0052428571428571324
pwm:
Client name,CTR,mean_diff
customeronewithverylongname,0.11291428571428572,-0.02935714285714286
customertwowithverylongname,0.03041428571428571,-0.001942857142857142
customerthree,0.01367142857142857,0.000700000000000001
customerfourwithverylongname,0.09828571428571428,0.0014285714285714457
customerfive,0.0053,0.0014999999999999987
customersixQuickSale,0.034525,0.005075000000000003
customerseven,0.1573,0.0052428571428571324
我想繪制一系列直方圖,在x軸上的客戶名稱,在y上的點擊率,而不會切斷xlabel。
我作圖並注意到xlabels被切斷了。 所以我讀了這個問題並以這種方式解決了:
plt.subplots_adjust(left=None, bottom=0.15, right=None, top=None, wspace=None, hspace=None)
我嘗試了不同的bottom
值:
0.35
而且每次xlabels更改位置時,我對xlabels的訂單順序都不相同。
相反,直方圖始終處於相同位置。
底部= 0.15
這是我的代碼的一部分
#defing the labels of the histograms
#pwm and lwm are the last & penultimate week dataframes
# with the weekly mean CTR for each customer
#defing the labels of the histograms
customer_list=set(lwm['Client name'])
x_pos=list(range(len(customer_list)))
x_lab=customer_list
width=0.4
#defining the y max heigh
max_y=max(zip(lwm['CTR'],pwm['CTR']))
#defining the histograms
fig,ax =plt.subplots(figsize=(8,6))
plt.bar(x_pos, pwm['CTR'], width, alpha=0.5, color='b',label=x_lab)
plt.bar([p + width for p in x_pos], lwm['CTR'], width, alpha=0.5, color='r', label=x_lab)
#defining the y max height
plt.ylim([0,max(max_y[0],max_y[1])*1.1])
plt.xticks(x_pos,x_lab,rotation=45, rotation_mode="anchor", ha="right")
plt.title('CTR Bar plot of the last week')
# Adding the legend and showing the plot
plt.legend(['Penultimate Week CTR','Last Week CTR', ], loc='best')
plt.subplots_adjust(left=None, bottom=0.15, right=None, top=None, wspace=None, hspace=None)
plt.show()
問題
xlabel由於set
改變了位置。
根據定義set
,是不同的可哈希對象的無序集合,但這並不意味着它是隨機排序的。 (有關詳細信息, 請參見此處https://stackoverflow.com/questions/2860339/can-pythons-set-absence-of-ordering-be-considered-random-order )。
因此您的輸出是正確的。
解決方案
您需要根據您的規格提取標簽,然后將其繪制出來。
例如使用:
customer_list=lwm['Client name']
代替
customer_list=set(lwm['Client name'])
這樣,您可以按x和y值的相同順序定義標簽。
0.15
0.25
請注意 ,如果想要特定的順序,則必須首先對數據集進行排序,然后提取圖的標簽,例如:
test1=lwm.sort_values(by=['CTR'], ascending=False)
test2=pwm.sort_values(by=['CTR'], ascending=False)
customer_list2=test1['Client name']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.