简体   繁体   English

如何更改 python 中日期时间数据的 x 轴刻度 label 的频率

[英]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()

My output我的 output 我的代码

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您只需要使用其他设置再玩一点

  • formatting the displayed date with matplotlib.dates.DateFormatter('%y') as you already didmatplotlib.dates.DateFormatter('%y')格式化显示的日期,就像你已经做的那样
  • setting the ticks of the x-axis to distinct values, either by using the function 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
  • limit the width of the x-axis with either 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]))

在此处输入图像描述

You need to specify ticks: xticks .您需要指定刻度: xticks For instance:例如:

plt.ticks([2012, 2013, 2014, 2015, 2016])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM