如何在matplotlib上为给定点设置x轴日期刻度标签

5

我正在尝试设置 x 轴上的日期刻度标签,仅适用于给定的点。例如,如果我有一个 datetime 列表作为 x 轴上的值:

x = [ datetime.datetime(..), ... , datetime.datetime()]

我尝试使用 ax.xaxis.set_ticklabels(x)

我想要对列表中的每一个六个点仅绘制日期,但是我得到了这个结果:

plot

我用以下代码获得了这个图表:

# figure's size in inch
fig = Figure(figsize=(8, 8))
# axes' position                                
ax = Axes(fig, [.1, .1, .8, .8])
ax.errorbar(matplotlib.dates.date2num(x), y, yerr=el['e'], fmt=format_string, label=label)

# shrinks current axis to 90%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.9, box.height])
# puts a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# autoscales axes following data limits
ax.autoscale(tight=False)

dateFmt = matplotlib.dates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(dateFmt)
monthsLoc = matplotlib.dates.MonthLocator()
daysLoc = matplotlib.dates.DayLocator(interval=1)
ax.xaxis.set_major_locator(monthsLoc)
ax.xaxis.set_minor_locator(daysLoc)
fig.autofmt_xdate(bottom=0.18)

# I tried to set tick labels with this but with no results
#ax.xaxis.set_ticklabels(x)
# adds axes to figure
fig.add_axes(ax)
# creates a canvas from figure
canvas = FigureCanvasAgg(fig)
# saves figure to filesystem in png format
canvas.print_figure(settings.MEDIA_ROOT + file_relative_path)

我做错了什么?

谢谢


2
它会失败,并显示“'Axes' object has no attribute 'set_ticks'”。但是ax.xaxis.set_ticks(x)可以工作 :) 谢谢 - gc5
1个回答

6

设置刻度和标签使用:

x = [ datetime.datetime(..), ... , datetime.datetime()]
ax.xaxis.set_ticks(x)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接