python - 如何使用 `set_major_locator` 将 x-ticks 设置为月份?

标签 python matplotlib

我正在尝试使用以下代码将 x-ticks 设置为 [Jan., Feb., ...]

import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, DateFormatter
fig = plt.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(np.arange(1000))
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))

我得到下图,没有 x-ticks enter image description here

我想知道为什么所有的 x-ticks 都消失了?我引用this implementation写了上面的代码

非常感谢。

最佳答案

不是很清楚你目前拥有的数据类型。但以下是我在 x 轴上绘制月份的建议:

  1. 使用 pd.to_datetime 转换您的日期
  2. 将其设置为您的数据框索引。
  3. 显式调用 plt.set_xticks() 方法

下面是一个重新创建数据的例子:

from datetime import datetime as dt
from datetime import timedelta

### create sample data
your_df = pd.DataFrame()
your_df['vals'] = np.arange(1000)

## make sure your datetime is considered as such by pandas
your_df['date'] = pd.to_datetime([dt.today()+timedelta(days=x) for x in range(1000)])
your_df=  your_df.set_index('date') ## set it as index

### plot it
fig = plt.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(your_df['vals'])
plt.xticks(rotation='vertical')
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))

enter image description here

请注意,如果您不想绘制每个月,您可以通过删除主要定位器让 matplotlib 为您处理。

fig = plt.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(your_df['vals'])
plt.xticks(rotation='vertical')
# ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))

enter image description here

已添加 进入提供的链接,您在使用的数据集 (boulder-precip.csv) 中确实有一个 DATE 字段。实际上,您可以按照相同的程序按月绘制:

df = pd.read_csv('boulder-precip.csv')
df['DATE'] = pd.to_datetime(df['DATE'])
df = df.set_index('DATE')

fig = plt.figure(figsize=[10, 5])
ax = fig.add_subplot(111)
ax.plot(df['PRECIP'])
plt.xticks(rotation='vertical')
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_major_formatter(DateFormatter('%b'))

enter image description here

关于python - 如何使用 `set_major_locator` 将 x-ticks 设置为月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57586693/

相关文章:

python - 使用Python在Hive中导入数据时出错

python - scikit-learn 适合大数据任务吗?

pandas - 如何在 MatPlotLib 中连接两组 XY 散点值?

matplotlib - Julia:如何使用 PyPlot 创建不同大小的子图?

python - x 和 y 必须具有相同的第一维,但具有形状 (1,) 和 (6,)

python - matplotlib 的上限/下限

python - 是否可以使用 matplotlib 在单独的窗口中显示多个图?

python - 如何使用 numpy loadtxt 加载多列?

python - 查找与另一个大列表重叠/相交的大列表的子集

python - 按列位置子集 dask 数据框