Search code examples
pythonmatplotlibaxis-labels

matplotlib set xticks to column, labels to corresponding index


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?


Solution

  • 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.