
我使用 Matplot lib 創建了上面的圖。
我想知道如何將 y-tick 標簽居中對齊(如果可能的話)。
我沒有成功嘗試:
for tick in ax[1].yaxis.get_majorticklabels():
tick.set_horizontalalignment("center")
非常感謝,感謝您的幫助
當前代碼如下:
#create plotting space
sns.set_style('whitegrid')
fig, ax = plt.subplots(figsize=(14,5),ncols=2)
fig.tight_layout()
#left plot
ax[0].barh(df_word_comp.index, df_word_comp.negative, align='center',color = '#d55e00')
ax[0].set_title('Negative Reviews',fontsize=14)
ax[0].invert_xaxis()
ax[0].invert_yaxis()
ax[0].yaxis.tick_right()
ax[0].yaxis.set_ticklabels([])
#right plot
ax[1].barh(df_word_comp.index, df_word_comp.positive, align='center',color = '#0072b2')
ax[1].set_title('Positive Reviews',fontsize=14)
ax[1].invert_yaxis()
ax[1].yaxis.tick_left()
ax[1].tick_params(axis='y',labelsize=13)
plt.suptitle('Word Frequency',y=0,fontsize=15, fontweight='bold')
plt.subplots_adjust(wspace=0.16);
uj5u.com熱心網友回復:

我使用 mpl_toolkits 的axisartist 管理了這個。 https://matplotlib.org/3.5.0/gallery/axisartist/demo_ticklabel_alignment.html
下面的完整代碼,但關鍵是ax2.axis["left"].major_ticklabels.set_ha("center")
不完美的代碼,所以如果有人看到我可以改進,請告訴我
import mpl_toolkits.axisartist as axisartist
#set figure
fig = plt.figure(figsize=(16,6))
#left plot
ax1=fig.add_subplot(121, axes_class = axisartist.Axes)
ax1.barh(df_word_comp.index, df_word_comp.negative, color = '#d55e00')
ax1.set_title('Negative Reviews',fontsize=14)
ax1.invert_yaxis()
ax1.invert_xaxis()
ax1.axis["left",'top'].toggle(all=False)
ax1.yaxis.set_ticklabels([])
#right plot
ax2=fig.add_subplot(122, axes_class = axisartist.Axes,)
ax2.barh(df_word_comp.index, df_word_comp.positive, color = '#0072b2')
ax2.set_title('Positive Reviews', fontsize=14)
ax2.axis["left"].major_ticklabels.set_ha("center")
ax2.axis["left"].major_ticklabels.set_fontsize(14)
ax2.axis["right",'top'].toggle(all=False)
ax2.invert_yaxis()
# plt.suptitle
plt.figtext(0.465,0.95,'Word Frequency',fontsize=15, fontweight='bold')
plt.subplots_adjust(wspace=0.17);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461698.html
標籤:matplotlib
