x轴python格式上的日期标签
我的数据看起来像这样x轴python格式上的日期标签,python,matplotlib,axis-labels,Python,Matplotlib,Axis Labels,我的数据看起来像这样 01.03.20 10 02.03.20 10 04.03.20 15 05.03.20 16 我想绘制日期与y值的对比,我想xaxis的格式类似于Mar 01Mar 02Mar 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.M
01.03.20 10
02.03.20 10
04.03.20 15
05.03.20 16
我想绘制日期
与y
值的对比,我想xaxis
的格式类似于Mar 01
Mar 02
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轴
、xticks
、和xlabel
,因此出现问题。如何更改xlabel
的格式以显示月份和日期,例如:2001年3月
02年3月
03年3月
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()
样本结果在这里
您的代码的输出是什么?请粘贴一个例子