How to change frequency of x-axis tick label of datetime data

1.7k Views Asked by At

I try to plot some speed time graph in spyder, and I did some plots. My problem is the x label. I want to write the time in the x plane as 2012 2013 2014 2015 2016 but I can't. 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 my code

What I want

what ı want

2

There are 2 best solutions below

3
On

You need to specify ticks: xticks. For instance:

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

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 did
  • 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(). Note that they should be of the same type as your original ticks (i.e. datetimes.date in this case)
  • limit the width of the x-axis with either plt.xlim() or ax.set_xlim()

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

enter image description here