Python Matplotlib:如何获得相同的;“基础”;及;抵销;轴记号和轴记号标签的参数
我想根据matplotlib中的日期范围绘制一系列值。我将tickPython Matplotlib:如何获得相同的;“基础”;及;抵销;轴记号和轴记号标签的参数,python,matplotlib,plot,axis-labels,Python,Matplotlib,Plot,Axis Labels,我想根据matplotlib中的日期范围绘制一系列值。我将tickbase参数更改为7,以便在每周开始时获得一个tick(plticker.IndexLocator,base=7)。问题在于setxticklabels函数不接受base参数。因此,第二个勾号(代表第2周开始的第8天)被标记为我的日期范围列表中的第2天,而不是应该的第8天(见图) 如何给出setxticklabelsabase参数 代码如下: my_data = pd.read_csv("%r_filename_%s_%s_%d_
base
参数更改为7,以便在每周开始时获得一个tick(plticker.IndexLocator,base=7
)。问题在于setxticklabels
函数不接受base
参数。因此,第二个勾号(代表第2周开始的第8天)被标记为我的日期范围列表中的第2天,而不是应该的第8天(见图)
如何给出setxticklabels
abase
参数
代码如下:
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)
图如下:
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)
你的标签坏掉的原因是。正确的方法是根据需要使用
格式化程序。由于每个数据点都有一个标签列表,因此可以使用。它似乎没有在线记录,但它有一个帮助:
class IndexFormatter(Formatter)
| format the position x to the nearest i-th label where i=int(x+0.5)
| ...
| __init__(self, labels)
| ...
因此,您只需将日期列表传递给IndexFormatter
。有一个最小的独立示例(numpy仅用于生成虚拟数据):
即使勾选位置发生变化,也应保持数据和标签配对:
我注意到您在调用setxticklabels
时也设置了标签的旋转,您现在会丢失这个。我建议改为使用,它似乎正是为了这个目的而设计的,不会弄乱你的ticklabel数据。你的ticklabel变差的原因是。正确的方法是根据需要使用格式化程序。由于每个数据点都有一个标签列表,因此可以使用。它似乎没有在线记录,但它有一个帮助:
class IndexFormatter(Formatter)
| format the position x to the nearest i-th label where i=int(x+0.5)
| ...
| __init__(self, labels)
| ...
因此,您只需将日期列表传递给IndexFormatter
。有一个最小的独立示例(numpy仅用于生成虚拟数据):
即使勾选位置发生变化,也应保持数据和标签配对:
我注意到您在调用setxticklabels
时也设置了标签的旋转,您现在会丢失这个。我建议改为使用,它似乎正是为了这个目的而设计的,不会弄乱你的标签数据。非常感谢-你的解决方案非常有效。对于其他人将来遇到相同问题的情况:我已经实现了上述解决方案,但也添加了一些代码,以便记号标签保持所需的旋转,并且(与左端)与相应的记号对齐。可能不是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")
非常感谢-您的解决方案非常有效。对于其他人将来遇到相同问题的情况:我已经实现了上述解决方案,但也添加了一些代码,以便记号标签保持所需的旋转,并且(与左端)与相应的记号对齐。可能不是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")