[英]How to set x-ticks to months with `set_major_locator`?
I am trying to use the following code to set the x-ticks
to [Jan., Feb., ...]我正在尝试使用以下代码将
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'))
I get the following figure, without x-ticks我得到下图,没有 x-ticks
I'm wondering why all x-ticks disappeared?我想知道为什么所有的 x-ticks 都消失了? I wrote the above code with reference to this implementation
我参考这个实现写了上面的代码
Many thanks.非常感谢。
It is not very clear the type of data you currently have.您目前拥有的数据类型不是很清楚。 But below are my suggestions for plotting the month on the x-axis:
但以下是我在 x 轴上绘制月份的建议:
pd.to_datetime
pd.to_datetime
转换您的日期plt.set_xticks()
methodplt.set_xticks()
方法Below one example with re-created data:下面是一个重新创建数据的示例:
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'))
Note that if you do not want every month plotted, you can let matplotlib handle that for you, by removing the major locator.请注意,如果您不想绘制每个月,您可以通过删除主要定位器让 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'))
Added Went into the link provided, and you do have a DATE
field in the dataset used ( boulder-precip.csv
).添加了进入提供的链接,并且您在使用的数据集中有一个
DATE
字段( boulder-precip.csv
)。 You can actually follow the same procedure and have it plotted on a monthly-basis:您实际上可以遵循相同的程序并按月绘制它:
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'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.