Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
x轴python格式上的日期标签_Python_Matplotlib_Axis Labels - Fatal编程技术网

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()
样本结果在这里


您的代码的输出是什么?请粘贴一个例子