[英]How to change frequency of x-axis tick label of datetime data in python
I try to plot some speed time graph in spyder, and I did some plots.我尝试在 spyder 中 plot 一些速度时间图,并且我做了一些绘图。 My problem is the x label.我的问题是 x label。 I want to write the time in the x plane as 2012 2013 2014 2015 2016
but I can't.我想将 x 平面上的时间写为2012 2013 2014 2015 2016
但我不能。 Here is my code这是我的代码
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
data=pd.read_excel("ts80.xlsx")
Date=data["Date"]
Speed=data["Speed"]
timestamp = pd.to_datetime(Date[0:]).dt.strftime("%Y %m %d")
fig, ax = plt.subplots(figsize=(13,6))
ax.plot(timestamp, Speed)
plt.xlabel("Time")
plt.ylabel("80Avg[m/s]")
plt.title("Mean Wind Speed at 80m")
plt.gca().xaxis.set_major_locator(mdates.DayLocator((1,15)))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y %m"))
plt.gcf().autofmt_xdate()
plt.show()
What I want我想要的是
You are on the right track following this post .在这篇文章之后,你走在了正确的轨道上。
You just need to play around a bit further with the other settings您只需要使用其他设置再玩一点
matplotlib.dates.DateFormatter('%y')
as you already did用matplotlib.dates.DateFormatter('%y')
格式化显示的日期,就像你已经做的那样matplotlib.pytplot.xticks()
or the method of an axis's object ax.set_ticks()
.通过使用 function matplotlib.pytplot.xticks()
ax.set_ticks()
轴的方法 ZA8CFDE6331BD59EB2AC96F8911C4BZ.66 将 x 轴的刻度设置为不同的值。 Note that they should be of the same type as your original ticks (ie datetimes.date
in this case)请注意,它们应该与您的原始刻度具有相同的类型(即在本例中为datetimes.date
)plt.xlim()
or ax.set_xlim()
使用plt.xlim()
或ax.set_xlim()
限制 x 轴的宽度I drew a little example here with different plots (see below)我在这里用不同的情节画了一个小例子(见下文)
import matplotlib.pyplot as plt
import numpy as np
import datetime
import matplotlib.dates as mdates
# create dummy data
y = np.random.randn(50)
x = [datetime.date.today() + datetime.timedelta(days=i) for i in range(len(y))]
# open figure
fig,axs = plt.subplots(2,2)
# flatten
axs = axs.flatten()
for i in range(4):
axs[i].plot(x,y)
# set x-axis date format
if i > 0:
myFmt = mdates.DateFormatter('%y')
axs[i].xaxis.set_major_formatter(myFmt)
# set x-axis ticks (to years)
if i > 1:
axs[i].set_xticks([datetime.date(i,1,1) for i in range(2020,2022)])
# limit x-axis again
if i > 2:
axs[i].set_xlim((x[0],x[-1]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.