Matplotlib,plotting pandas系列:AttributeError:“tuple”对象没有属性“xaxis”

2024-05-23 17:40:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在绘制熊猫系列数据,其中记录了1981年每周“事件”的总和。这个系列被命名为“每周数据”。

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

我想按年和周放置蜱虫。当我试图绘制此图时,会收到一个属性错误:

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'

我该怎么解决?

编辑:继迈克·穆勒之后,上面的错误是plt.subplot(111)。然而,我仍然不能让每周的节拍工作。也许我们需要使用ax.set_xticks(major_ticks)ax.set_xticks(minor_ticks, minor=True)

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

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

我自己也很困惑


Tags: 数据true错误绘制pltaxsetminor
1条回答
网友
1楼 · 发布于 2024-05-23 17:40:13

你正在创建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))

每四个月才显示一次。

相关问题 更多 >