matplotlib将xticks设置为列,将标签设置为对应的索引 [英] matplotlib set xticks to column, labels to corresponding index

查看:206
本文介绍了matplotlib将xticks设置为列,将标签设置为对应的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对matlpotlib还是很陌生,我发现刻度线定位器和标签令人困惑,所以请多多包涵.我发誓我已经搜索了几个小时.

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.

我将其转换为图

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

我需要将x轴用作数值,因为我想稍后添加一个散点图,这对于字符串值是不可能的.

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')

这行得通

所以基本上,我希望我的xticks是"dayofweek"列,而它们的标签是对应的索引. 现在,如果我通过以下方式手动设置_xticklabels:

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)

标签从轴上的位置0开始.

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?

推荐答案

直接的解决方案不仅是设置xticklabel,还包括刻度本身:

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)

使用FixedLocator和FixedFormatter可以实现同样的效果,

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.

这篇关于matplotlib将xticks设置为列,将标签设置为对应的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆