python - 如何在 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)
,但它们似乎都没有做我正在寻找的东西。
解决方案
- 您只有 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')
推荐阅读
- c++ - 如何重复打印相同的值?
- ruby-on-rails - 通过关联创建操作有很多通过关联来分配喜爱的类别
- node.js - 如何在不进一步连接数据库的情况下使用生成的数组?节点js
- ios - 在 loadView() 中声明变量时出现“使用未解析的标识符”错误
- angular - 角度单文件组件是否支持 sass/scss?
- jenkins - Jenkins 在从节点上构建失败,出现“java.io.EOFException”
- git - 如何首先使用 git ls-files 显示目录
- django - 当我用 nginx+uwsgi 部署 django 项目时,总是出现“502 bad gateway error”。是什么原因?
- r - 如何返回数字向量的迄今为止最小值的向量?
- python - 如何将 2D 数组中的每个元素乘以 -1?