x轴python格式上的日期标签

时间:2020-03-10 20:38:37

标签: python matplotlib axis-labels

我的数据看起来像这样

01.03.20    10
02.03.20    10
04.03.20    15
05.03.20    16

我想绘制datesy的值,并且希望xaxis的格式类似于Mar 01 Mar 02 {{ 1}} ...

这是我的代码:

Mar 03

由于fig, ax = plt.subplots() ax.scatter(x, y, s=100, c='C0') ax.plot(x, y, ls='-', c='C0') # Set the locator locator = mdates.MonthLocator() # every month # Specify the format - %b gives us Jan, Feb... fmt = mdates.DateFormatter('%b-%d') X = plt.gca().xaxis X.set_major_locator(locator) # Specify formatter X.set_major_formatter(fmt) ax.xaxis.set_tick_params(rotation=30) x-axisxticks未显示,所以出现了错误。如何更改xlabel的格式以显示月份和日期,例如:xlabel Mar 01 Mar 02 ...

1 个答案:

答案 0 :(得分:2)

1)我假设您的x轴包含string,而不是datetime。然后,在绘制之前,我将其转换如下。

x=[datetime.strptime(xi, "%d.%m.%y") for xi in x]

2)如果选择MonthLocator,则无法将其作为3月1日...因此,请用DayLocator进行切换。

locator = mdates.DayLocator()

3)此选项是可选的,以使代码更简洁。您不需要X

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(fmt)
ax.xaxis.set_tick_params(rotation=30)

示例代码在这里。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

x=["01.03.20", "02.03.20", "04.03.20", "05.03.20"]
x=[datetime.strptime(xi, "%d.%m.%y") for xi in x]
y=[10, 10, 15,16]

fig, ax = plt.subplots()
ax.scatter(x, y, s=100, c='C0')
ax.plot(x, y, ls='-', c='C0')

locator = mdates.DayLocator() 
fmt = mdates.DateFormatter('%b-%d')

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(fmt)
ax.xaxis.set_tick_params(rotation=30)
ax.set_xlim(x[0],x[3])

plt.show()

样本结果在这里。

enter image description here