2

I am pretty new to matlpotlib and I find the tick locators and labels confusing, so please bear with me. I swear I've been googling for hours.

I have a dataframe 'frame' like this (relevant columns):

dayofweek   sla
weekday         
Mon     1   0.889734
Tue     2   0.895131
Wed     3   0.879747
Thu     4   0.935000
Fri     5   0.967742
Sat     6   0.852941
Sun     7   1.000000

where the weekday name is the index and the weekday number is a column. There are no datetime objects in this frame.

I turn this into a plt.figure

fig=plt.figure(figsize=(7,5))    
ax=plt.subplot(111)

I need to have my x-axis as numeric values, because I want to add a scatter plot later, which is not possible with string values.

x_=frame.dayofweek.values
anbar=ax.bar(x_,y_an,width=0.8,color=an_c,label='angekommen')

This works ok xticks are 'dayofweek'

So basically I want my xticks to be the 'dayofweek' column and their labels to be the corresponding index. Now if I set_xticklabels manually by

ax.set_xticklabels(frame.index)

the labels start from position 0 on the axis.

enter image description here

I can work around this by rearranging the list of labels, but there should be a 'correct' way to use the Locators or Formatter, but (see above) this is quite confusing for me. Can someone point me to how I make the labels correspond to their index?

badlands
  • 115
  • 1
  • 10
  • For future questions: The quality of the question can be further enhanced by further stripping down your example. In this case a full working example can be accomplished in only 6 lines of code. This makes it easier for people answering your question, but also makes your question a more general reference for others that have a similar problem. – Tom de Geus May 01 '17 at 10:48

1 Answers1

10

The straight forward solution is to not only set the xticklabels but also the ticks themselves:

ax.set_xticks(frame.dayofweek.values)
ax.set_xticklabels(frame.index)

The same can be accomplished with a FixedLocator and a FixedFormatter,

ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator(frame.dayofweek.values))
ax.xaxis.set_major_formatter(matplotlib.ticker.FixedFormatter(frame.index))

but seems quite unnecessary for this simple task.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thanks for that, really quite simple, works perfectly. I guess I've read somewhere in the matplotlib docs that set_xticks is discouraged so I kept away from it. Maybe the question is of use for someone in the future nonetheless. Cheers – badlands May 01 '17 at 10:53
  • set_xticks is discouraged in many cases because it replaces the ScalarFormatter with a FixedFormatter and that is often undesired. But here it is exactly what you want, I suppose. – ImportanceOfBeingErnest May 01 '17 at 10:55
  • Absolutely. I tried fiddling with the locators, but honestly that's over my head right now, so thanks for answering that uneducated question ;) – badlands May 01 '17 at 11:08