【问题标题】:pyplot does not have attribute 'xaxis_set_major_formatter'pyplot 没有属性“xaxis_set_major_formatter”
【发布时间】:2020-06-14 12:27:43
【问题描述】:

我正在尝试使用此代码在 x 轴 [在这张图片中] 绘制小时数

#create a lineplot
fig = plt.figure(figsize=(20,5))
ax = fig.add_subplot()
plt.title('SUBIC-NAIA Air Temp Difference. (C)')
ax.plot(date_rng,NASU_dif)
monthyearFmt = mdates.DateFormatter('%Y-%m-%d-%h')
plt.xaxis_set_major_formatter(monthyearFmt)
plt.xlabel('Time Step (hr)')
plt.ylabel('Air Temperature (m/s)')
plt.legend(loc='upper right', prop={'size': 10})
plt.show()

但我收到了

AttributeError: 模块 'matplotlib.pyplot' 没有属性 'xaxis_set_major_formatter'

我有一个日期作为我的索引。这个怎么解决?

DatetimeIndex(['2018-04-22 00:00:00', '2018-04-22 01:00:00', '2018-04-22 02:00:00', '2018-04-22 03:00:00', '2018-04-22 04:00:00', '2018-04-22 05:00:00', '2018-04-22 06:00:00', '2018-04-22 07:00:00', '2018-04-22 08:00:00', '2018-04-22 09:00:00', ... '2018-04-29 15:00:00', '2018-04-29 16:00:00', '2018-04-29 17:00:00', '2018-04-29 18:00:00', '2018-04-29 19:00:00', '2018-04-29 20:00:00', '2018-04-29 21:00:00', '2018-04-29 22:00:00', '2018-04-29 23:00:00', '2018-04-30 00:00:00'], dtype='datetime64[ns]', length=193, freq='H')

【问题讨论】:

标签: python datetime xticks


【解决方案1】:

应该是xaxis.set_major_formatter

另外,xaxisax 的财产。所以你可以这样做

ax.xaxis.set_major_formatter(monthyearFmt)

【讨论】:

  • 您好,感谢您的回复。我没有注意到'_'部分。虽然,即使在使用 xaxis.set_major_formatter 之后,我得到模块“matplotlib.pyplot”没有属性“xaxis”
  • @kaelel18 注意axxaxis 是轴的属性,而不是 pyplot
【解决方案2】:

Axis 对象上找到set_major_formatter 方法(例如ax.xaxis)。

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d-%h'))

如果不使用子图,可以通过gca()方法访问轴对象(获取当前轴)

from matplotlib import pyplot as plt
import matplotlib.dates as mdates
    
plt.plot(... 

ax = plt.gca()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d-%h'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2012-12-01
    • 1970-01-01
    • 2011-04-14
    • 2020-01-06
    • 1970-01-01
    相关资源
    最近更新 更多