首页 > 解决方案 > 如何在 x 轴上仅显示 12 个数据点的月份

问题描述

当我有 365 个数据点时,我可以使用以下代码创建一个带有月份名称的图:

y = np.random.normal(size=365)
x = np.array(range(len(y)))
plt.plot(x, y)
plt.xlabel('Month')
locator = mdates.MonthLocator()
fmt = mdates.DateFormatter('%b')
X = plt.gca().xaxis
X.set_major_locator(locator)
X.set_major_formatter(fmt)

这是结果,这正是我正在寻找的: 在此处输入图像描述

我想做同样的事情,但只有 12 个数据点(每个月一个)。如果我只是将 365 更改为 12 ( y = np.random.normal(size=12)),它看起来像这样:

在此处输入图像描述

我怎样才能让它在 x 轴上显示第一张图中的所有月份?

我尝试将参数传递给MonthLocator (bymonth, bymonthday, interval),但它们似乎都没有做我正在寻找的东西。

标签: pythonmatplotlib

解决方案


  • 您只有 12 分,因此MonthLocator无法按预期工作。
  • 将 x 轴设置为带有列表的月份名称会更容易:
    • import calendar获取月份名称列表,或手动键入它们,然后使用x = calendar.month_abbr[1:]
import calendar  # part of the standard library
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(365)
y = np.random.normal(size=12)
x = calendar.month_abbr[1:]
plt.plot(x, y)
plt.xlabel('Month')

在此处输入图像描述


推荐阅读