【问题标题】:How to change frequency of x-axis tick label of datetime data in python如何在python中更改日期时间数据的x轴刻度标签的频率
【发布时间】:2021-03-24 13:03:56
【问题描述】:

我尝试在 spyder 中绘制一些速度时间图,并绘制了一些图。我的问题是 x 标签。我想将 x 平面上的时间写为2012 2013 2014 2015 2016,但我不能。这是我的代码

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()

我的输出

我想要什么

【问题讨论】:

  • 欢迎来到stackoverflow!您应该始终包含minimal working example,即不要从您的硬盘读取数据,而是编写一些生成玩具示例的代码。

标签: python pandas matplotlib plot spyder


【解决方案1】:

您在this post 之后走在正确的轨道上。

您只需要进一步调整其他设置

  • matplotlib.dates.DateFormatter('%y') 格式化显示的日期,就像你已经做的那样
  • 通过使用函数matplotlib.pytplot.xticks() 或轴对象ax.set_ticks() 的方法将x 轴的刻度设置为不同的值。请注意,它们的类型应与您的原始刻度相同(即在本例中为 datetimes.date
  • 使用plt.xlim()ax.set_xlim() 限制x 轴的宽度

我在这里用不同的情节画了一个小例子(见下文)

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]))

【讨论】:

    【解决方案2】:

    您需要指定刻度:xticks。例如:

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

    【讨论】:

    • 我试过了,但是模块'matplotlib.pyplot'没有属性'ticks'的错误。你能写出所有的代码吗?我是初学者。感谢您的理解。
    • 不是“ticks”,是“xticks”。
    • 它不工作。我写了 plt.xticks([2012, 2013, 2014, 2015, 2016]) 这是我得到的。 ibb.co/Qv92n6R
    猜你喜欢
    • 2017-07-15
    • 2018-01-24
    • 2020-04-11
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    相关资源
    最近更新 更多