python - Matplotlib,绘制 pandas 系列 : AttributeError: 'tuple' object has no attribute 'xaxis'

标签 python matplotlib attributeerror

我正在绘制 Pandas 系列数据,该数据记录了 1981 年每周“事件”的总和。该系列被命名为“weekly_data”。

1981-03-16    1826
1981-03-23    1895
1981-03-30    1964
1981-04-06    1978
1981-04-13    2034
1981-04-20    2073
1981-04-27    2057
dtype: int64

我想按年和按周放置刻度。当我尝试绘制此图时,我收到一个 AttributeError:

fig = plt.figure(figsize=(12,5))
ax = plt.subplots(111)
plt.plot(weekly_data, color = 'green' )
yloc = YearLocator()
mloc = MonthLocator()
ax.xaxis.set_major_locator(yloc)
ax.xaxis.set_minor_locator(mloc)
ax.grid(True)
plt.show()

错误是

AttributeError                            Traceback (most recent call last)
<ipython-input-92-843dbab30ed7> in <module>()
      6 yloc = YearLocator()
      7 mloc = MonthLocator()
----> 8 ax.xaxis.set_major_locator(yloc)
      9 ax.xaxis.set_minor_locator(mloc)
     10 ax.grid(True)

AttributeError: 'tuple' object has no attribute 'xaxis'

我该如何解决这个问题?

编辑:根据 Mike Mueller,上面的错误是 plt.subplot(111) 。但是,我仍然无法让每周的滴答声正常工作。也许我们需要使用ax.set_xticks(major_ticks)ax.set_xticks(minor_ticks, minor=True)

这是我从 1991 年开始绘制的 pandas 系列数据

Datetime
1990-12-23    1980
1990-12-30    1860
1991-01-06    1761
1991-01-13    1792
1991-01-20    1825
....
dtype: int64

这是代码

fig = plt.figure(figsize=(12,5))
ax = plt.subplot(111)
plt.plot(weekly_data1991, color = 'green' )
yloc = YearLocator()
mloc = MonthLocator()
ax.xaxis.set_major_locator(yloc)
ax.xaxis.set_minor_locator(mloc)
ax.grid(True)
plt.show()

这是绘图输出

enter image description here

我自己也很困惑

最佳答案

您正在创建 111 个子图。变化:

ax = plt.subplots(111)

进入:

ax = plt.subplot(111)

你应该可以工作。它创建一个由一行、一列和一个子图组成的子图数组。例如,这个:

plt.subplot(231)
plt.subplot(236)

在 2 行 3 列的数组中创建子图 1 和子图 6:

enter image description here

您可以通过以下方式使月份可见:

ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter('%B'))

年份和月份相互打印。一种解决方案是将年份放在顶部,月份放在底部:

ax.xaxis.set_tick_params(labeltop='on', labelbottom='off')

用途:

mloc = matplotlib.dates.MonthLocator(range(1, 12, 4))

每四个月仅显示一次。

关于python - Matplotlib,绘制 pandas 系列 : AttributeError: 'tuple' object has no attribute 'xaxis' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34388800/

相关文章:

python - 从元组列表中搜索元组索引

python - Matplotlib:获取子图位置值(hspace,wspace,..)

python - 使用\w+ 在正则表达式搜索中包含 '-'。 Python

python - 为什么我打包的 eel 应用程序执行失败 : AttributeError: 'NoneType' object has no attribute 'write'

Python Tkinter 返回

python - 如何在不打开新选项卡的情况下更改 Selenium 中的 URL (python)?

python - Matplotlib 副标题打印旧标题

python - 属性错误:模块 'pandas.tseries.frequencies' 没有属性 'is_subperiod'

python - 使用 --onefile 选项在 PyInstaller 上捆绑 CEFpython

matplotlib - (如何)可以使 matplotlib 图仅响应一维的 "zoom"导航?