简体   繁体   中英

Ticklabels inside a plot in matplotlib

I have a barchart, where the tick labels on the 'y' axes are outside. Example However, I would like to have the ylabels inside the bars with an align to the left. Is there a way to do this? Here is the code:

fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center',
        color='green', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

If I play with tick_params:

ax.tick_params(axis='y', direction='in',pad=-5)

I get

这个

which is not what I want since the text is underneath and still aligned to the right.

This is a matter of setting the correct parameters.

  • Alignment is set for the ticklabels,

     ax.set_yticklabels(people, horizontalalignment = "left") 
  • Padding needs to be much larger, eg pad = -15 to have the label inside the axes.

This would already give you the desired graph.

在此处输入图片说明

However, since you seem to be using the seaborn-darkgrid style the labels are behind the bars. To bring them in front you can set,

plt.rcParams["axes.axisbelow"] = "line"

Additionally it might make sense to turn the y grid off , which would otherwise strike through the textlabels.

plt.rcParams["axes.grid.axis"] ="x"

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM