2016-06-23 146 views
0

我想在matplotlib中针对日期范围绘制一系列值。我将勾选base参数更改为7,以在每周开始时得到一个勾号(plticker.IndexLocator, base = 7)。问题是set_xticklabels函数不接受base参数。因此,第二个记号(代表第2周开始的第8天)在我的日期范围列表中标记为第2天,而不是第8天(如图所示)。Matplotlib:如何为坐标轴和坐标轴刻度标签获取相同的“基准”和“偏移量”参数

如何给set_xticklabels a base参数?

下面是代码:

my_data = pd.read_csv("%r_filename_%s_%s_%d_%d.csv" % (num1, num2, num3, num4, num5), dayfirst=True) 
my_data.plot(ax=ax1, color='r', lw=2.) 
loc = plticker.IndexLocator(base=7, offset = 0) # this locator puts ticks at regular intervals 
ax1.set_xticklabels(my_data.Date, rotation=45, rotation_mode='anchor', ha='right') # this defines the tick labels 
ax1.xaxis.set_major_locator(loc) 

这里的情节:

Plot

回答

0

您ticklabels坏了的原因是setting manual ticklabels decouples the labels from your data。正确的做法是根据您的需要使用Formatter。由于您有每个数据点的标签列表,因此您可以使用IndexFormatter。这似乎是在网上无证,但它有一个帮助:

class IndexFormatter(Formatter) 
| format the position x to the nearest i-th label where i=int(x+0.5) 
| ... 
| __init__(self, labels) 
| ... 

所以,你只需要您的日期列表传递给IndexFormatter。具有最小,大熊猫无关的例子(与numpy的仅用于生成虚拟数据):

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib as mpl 


# create dummy data  
x = ['str{}'.format(k) for k in range(20)] 
y = np.random.rand(len(x)) 

# create an IndexFormatter with labels x 
x_fmt = mpl.ticker.IndexFormatter(x) 

fig,ax = plt.subplots() 
ax.plot(y) 
# set our IndexFormatter to be responsible for major ticks 
ax.xaxis.set_major_formatter(x_fmt) 

这应该让您的数据和对标签,即使勾选持仓变化:

result

我注意到你也可以在set_xticklabels的调用中设置标签标签的旋转角度,你现在就会失去这个。我建议使用fig.autofmt_xdate来代替它,它似乎是专门为此目的而设计的,而不会混淆您的ticklabel数据。

0

非常感谢 - 您的解决方案完美的作品。对于其他人在将来遇到同样问题的情况:我已经实现了上述解决方案,但还添加了一些代码,以便滴答标签保持所需的旋转状态并且还将(与它们的左端)对齐到相应的滴答。可能不是pythonic,可能不是最佳实践,但它的工作原理

x_fmt = mpl.ticker.IndexFormatter(x) 
ax.set_xticklabels(my_data.Date, rotation=-45) 
ax.tick_params(axis='x', pad=10) 
ax.xaxis.set_major_formatter(x_fmt) 
labels = my_data.Date 
for tick in ax.xaxis.get_majorticklabels(): 
    tick.set_horizontalalignment("left") 
相关问题