【问题标题】:MonthLocator in MatplotlibMatplotlib 中的 MonthLocator
【发布时间】:2017-03-19 00:44:03
【问题描述】:

我有这样的情节:

我想更改 12 个位置的刻度,以这种格式表示各自的月份:Jan-Feb_Mar...

当我使用 MonthLocator 功能时,刻度会从绘图中消失

ax = plt.gca()
ax.set_xlim([0, 365])
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))

我不知道这段代码的错误在哪里。谢谢

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您的代码的主要问题是 x 轴由数字组成。如果您使用日期的格式化程序,则轴也必须有日期。

from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter
from matplotlib.dates import MonthLocator, DateFormatter
import numpy as np

# example data
x = np.arange(0,366,1)
y = np.random.uniform(-100,100,len(x)) 

# generate list of dates from 01.01.2017 to 01.01.2018 through 1 day
dates = list()
dates.append(datetime.strptime('2017-01-01', '%Y-%m-%d'))
for d in x[1:]:
    dates.append(dates[0] + timedelta(days = d))

# plot with dates not x!
plt.plot(dates,y)
ax = plt.gca()

# set dates limits
ax.set_xlim([dates[0], dates[-1]])

# formatters' options
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(NullFormatter())
ax.xaxis.set_minor_formatter(DateFormatter('%b'))
plt.show()

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2021-09-25
    • 2018-07-12
    • 2022-01-22
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多