我有这样的情节:
我想更改 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'))
Run Code Online (Sandbox Code Playgroud)
我不知道这段代码中的错误在哪里。谢谢
您的代码的主要问题是 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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9726 次 |
| 最近记录: |