Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e. 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, e.g.:

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.

like image 459
its_broke_again Avatar asked Dec 20 '25 03:12

its_broke_again


1 Answers

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:

enter image description here

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)
like image 107
Tom de Geus Avatar answered Dec 22 '25 18:12

Tom de Geus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!