I am trying to plot average temperatures from 1960 to 2021 for the month of December from time series data. my dataframe contains mean minimum and mean maximum temperatures, as
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
tem_december_monthly_mean
Max Min
Date
1960-12-31 20.900000 1.800000
1961-12-31 17.400000 1.670968
1962-12-31 18.354839 3.035484
1963-12-31 20.280645 3.616129
1964-12-31 18.961290 3.725806
... ... ...
2017-12-31 20.354839 3.929032
2018-12-31 18.664516 2.687097
2019-12-31 17.993548 2.645161
2020-12-31 19.605000 5.025000
2021-12-31 19.870968 2.880645
for plotting i am trying as,
fig, ax=plt.subplots(figsize=(12,8))
ax.plot(tem_dec_monthly_mean.index,
tem_dec_monthly_mean["Min"], color="k")
for formatting dates on x-axis, i am trying as,
my_formate = DateFormatter("%d-%m")
ax.xaxis.set_major_formatter(my_formate)
ax.xaxis.set_major_locator(mdates.MonthLocator()
ax.xaxis.set_minor_locator(mdates.WeekdayLocator())
but this gives me very messy x-axis ticks (all dates from 1960-2021), but i want to show only the days of December because this dataset is for the month of December.
can someone guide me for how to show only days of December on x-axis by using Dateformatter or any other way to get my desire formatting
CodePudding user response:
Since it is difficult to distinguish the year when only the month and day are lined up, I use YearLocator() to specify the month and day, and then format the lines to be lined up vertically, with 3-year intervals to make it easier to read. Adding a grid makes it even easier to read.
fig, ax=plt.subplots(figsize=(12,8))
ax.plot(tem_dec_monthly_mean['Date'], tem_dec_monthly_mean["Min"], color="k")
years = mdates.YearLocator(base=3, month=12, day=31)
yearss_fmt = mdates.DateFormatter('%d\n%b\n%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.grid(axis='x')
plt.show()

