Skip to main content
 首页 » 编程设计

python之在 matplotlib 中使用线图时用日期替换 X 轴上的数字

2024年10月25日8xing901022

我正在绘制一个带有数字数组的直线图

fig, ax = plt.subplots() 
ax.plot(x, 0 * x) 

x 是数组:

array([  0,1,2,3,4,5,6,7,8,9,10 ]) 

该行很好,但我想在 x 轴上显示日期。我想关联 每个数字的日期并将其用作我的 x 刻度。

谁能给点建议?

请您参考如下方法:

你可以控制the ticker format 任意值 using a ticker.FuncFormatter :

import matplotlib.ticker as ticker 
def todate(x, pos, today=DT.date.today()): 
    return today+DT.timedelta(days=x) 
fmt = ticker.FuncFormatter(todate) 
ax.xaxis.set_major_formatter(fmt) 

如果日期显得太拥挤,您可以轮换:

fig.autofmt_xdate(rotation=45)   

例如,

import datetime as DT 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
import matplotlib.ticker as ticker 
 
x = np.array([0,1,2,3,4,5,6,7,8,9,10]) 
 
fig, ax = plt.subplots(figsize=(7, 4)) 
ax.plot(x, x**2*np.exp(-x)) 
def todate(x, pos, today=DT.date.today()): 
    return today+DT.timedelta(days=x) 
fmt = ticker.FuncFormatter(todate) 
ax.xaxis.set_major_formatter(fmt) 
fig.autofmt_xdate(rotation=45)   
plt.show() 

产量