matplotlib X and Y-axises is duplicated when major_formatter is set

pod7payv  于 2023-02-23  发布在  其他
关注(0)|答案(1)|浏览(153)

I have a code to plot an empty graph:

from datetime import datetime, timedelta
from matplotlib import pyplot, dates

pyplot.yticks([0,1,2,3,4])

ts_start = datetime.now() - timedelta(hours=1)
ts_end = datetime.now()
delta = timedelta(minutes=10)

x_dates = dates.drange(ts_start, ts_end, delta=delta)
pyplot.xlim(x_dates[0], x_dates[-1])
# fmt = dates.DateFormatter('%Y-%m-%d %H:%M:%S')
# pyplot.axes().xaxis.set_major_formatter(fmt)

pyplot.tick_params(axis='x', labelrotation=30)
pyplot.xticks(x_dates)

pyplot.show()

I want to display time in format '%Y-%m-%d %H:%M:%S' on y-axis, not int.
But when adding major_formatter to xaxis (commented lines) I get duplicated X/Y axes (+xlim/ylim crashes):

pyplot.xticks()/pyplot.yticks() call return my ticks with timestamps/int.
How to do without set_major_formatter?

xzlaal3s

xzlaal3s1#

pyplot.axes()创建新的轴。如果你想得到当前的轴,要么在显式创建它们的时候保存一个句柄(目前你没有这样做),要么使用pyplot.gca()来得到当前的轴。
建议明确以下事项:

fig = plt.figure(figsize=(6, 3.5))

ax = fig.add_subplot()  # or use the optional arguments to put more than one axes in the figure

ax.plot(...)
ax.set_xlim(...)
ax.set_xticks(...)
ax.xaxis.set_major_formatter(...)

这样就可以清楚地看到应用的对象,尤其是在有多个图形和轴的情况下。
无论如何,pyplot中的函数(例如pyplot.xticks())大多只是轴上函数(例如ax.set_xticks())的薄 Package 器。

相关问题