Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...