简体   繁体   English

如何在 matplotlib 中格式化 x 轴上的日期?

[英]how to format dates on x-axis in matplotlib?

I am trying to plot average temperatures from 1960 to 2021 for the month of December from time series data.我正在尝试从时间序列数据中得出 1960 年至 2021 年 12 月份的 plot 平均温度。 my dataframe contains mean minimum and mean maximum temperatures, as我的 dataframe 包含平均最低和平均最高温度,如

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,对于在 x 轴上格式化日期,我正在尝试,

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.但这给了我非常混乱的 x 轴刻度(所有日期从 1960 年到 2021 年),但我只想显示 12 月的日子,因为这个数据集是 12 月的。 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有人可以指导我如何使用Dateformatter或任何其他方式在 x 轴上仅显示 12 月的几天来获得我想要的格式

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.由于只排月日很难区分年份,所以我使用YearLocator()指定月日,然后将行格式化为垂直排列,以 3 年为间隔更容易读书。 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()

在此处输入图像描述

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

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