简体   繁体   中英

Changing x-axis labels in errorbar plot: no attribute 'get_xticklabels'

I am trying to plot some data the main plot information is

ax1 = plt.errorbar(df1.index, df1['Mean'],
               yerr=df1['SD'], color='black', linestyle='-')
ax2 = plt.errorbar(df2.index, df2['Mean'],
               yerr=df2['SD'], color='grey', linestyle='-')

The problem is each data frame index is 5% increments of a whole (ie df1 index is 0,5,10...100 as is df2) the result is the plot is trying to cram 40 labels on the x-axis

I have tried a few different approaches but none have worked so far. For example trying to rotate the labels and reduce font size, eg:

plt.setp(ax1.get_xticklabels(), rotation='vertical', fontsize=7)

returns

AttributeError: 'ErrorbarContainer' object has no attribute 'get_xticklabels'

I get the same error if I try to alter the x axis of ax1 and ax2 using tick_params

I think it may be because the plot is seeing the x-axis as categorical but I'm stumped on how to fix it?

Ideally I would like to just show the 0, 25, 50, 75 and 100% labels for ax1 and ax2, but at this point I'd be happy with just rotating them so they look better.

The problem is that you are using the handle of the plot (of errorbar ) and not the handle of the axis. There are two ways to get the handle of the axis:

  1. When creating the figure (or axis in fact).
  2. At any time you can get the handle of the current axis using plt.gca() .

An example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.errorbar([0,1,2], [0,1,2], yerr=[.01,.05,.1])
ax.errorbar([0,1,2], [0,2,4], yerr=[.01,.05,.1])

plt.setp(ax.get_xticklabels(), rotation='vertical', fontsize=7)

plt.show()

This would result in:

在此处输入图片说明

If you want the use the handle of the current axis you could also have used:

plt.setp(plt.gca().get_xticklabels(), rotation='vertical', fontsize=7)

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