Home > Software design >  Matplotlib center align y tick labels
Matplotlib center align y tick labels

Time:04-22

enter image description here

I have created the above plot using Matplot lib.
I would like to know how to centre align the y-tick labels (if it is possible).
I have unsuccessfully tried:

for tick in ax[1].yaxis.get_majorticklabels():
    tick.set_horizontalalignment("center")

Many thanks, your help is appreciated

Current code below:

#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);

CodePudding user response:

enter image description here

I managed this using axisartist from mpl_toolkits. https://matplotlib.org/3.5.0/gallery/axisartist/demo_ticklabel_alignment.html

Full code below but the key line is ax2.axis["left"].major_ticklabels.set_ha("center")

Not perfect code, so if anyone sees how I could improve, please let me know

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);
  • Related