matplotlib set xticks to column, labels to corresponding index

橙三吉。 提交于 2019-12-03 22:28:41

问题


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

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.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/43717739/matplotlib-set-xticks-to-column-labels-to-corresponding-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!