![](/img/trans.png)
[英]How to display dates in matplotlib x-axis instead of sequence numbers
[英]How can I display dates on the x axis in matplotlib?
我有 1994 年 1 月 1 日至 2000 年 4 月 30 日的每日數據。 我有日期時間格式的日期,但是當我 plot 一行 plot 與 x 軸上的時間和 y 軸上的變量時,matplotlib 在 x 軸上打印太多。 如何通過繪圖日期解決此問題?
到目前為止,我已經這樣做了:
# get the proper dates
from datetime import timedelta, date
def daterange(date1, date2):
for n in range(int ((date2 - date1).days)+1):
yield date1 + timedelta(n)
# jan 1st 1994 - april 30th 2000
start_dt = date(1994,1,1)
end_dt = date(2000,4,30)
dates = []
for dt in daterange(start_dt, end_dt):
dates.append(dt.strftime("%Y-%m-%d"))
#print(dt.shape)
dates = np.array(dates)
random = np.random.rand(dates.size)
plt.plot(dates,random)
plt.show()
我如何 plot 日期以便您可以看到 xticks?
讓我們從必要的導入開始:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
首先要糾正的是您創建源數據的方式:
您可以通過以下方式實現它:
np.random.seed(1) # To get repeatable results
dates = pd.date_range('1994-01-01', '2000-04-30')
s = pd.Series(np.random.rand(dates.size), index=dates)
然后是關於圖像的注釋:由於您有每日數據,因此您應該只打印每個第 n 個點,例如s[::20]
。 否則圖像將不可讀。
要獲取帶有日期的圖像,您可以運行例如:
plt.plot(s[::20])
plt.xticks(rotation=30)
plt.gca().xaxis.set_minor_locator(mdates.MonthLocator(bymonth=[4,7,10]));
注意事項:
plt.xticks(rotation=30)
。對於上述源數據,我得到了以下圖像:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.