如何在 matplotlib 中格式化 x 轴上的日期?
how to format dates on x-axis in matplotlib?
我正在尝试根据时间序列数据绘制 1960 年到 2021 年 12 月份的平均气温。我的数据框包含平均最低温度和平均最高温度,如
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
对于我正在尝试的绘图,
fig, ax=plt.subplots(figsize=(12,8))
ax.plot(tem_dec_monthly_mean.index,
tem_dec_monthly_mean["Min"], color="k")
为了在 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())
但这给了我非常混乱的 x 轴刻度(所有日期从 1960 年到 2021 年),但我只想显示十二月的日子,因为这个数据集是十二月的。
有人可以指导我如何通过使用 Dateformatter
或任何其他方式获得我想要的格式
在 x 轴上仅显示 12 月的天数吗
由于只排月日很难区分年份,所以我用YearLocator()
指定月日,然后格式化要竖排的行,3 -年间隔,以使其更易于阅读。添加网格使其更易于阅读。
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()
我正在尝试根据时间序列数据绘制 1960 年到 2021 年 12 月份的平均气温。我的数据框包含平均最低温度和平均最高温度,如
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
对于我正在尝试的绘图,
fig, ax=plt.subplots(figsize=(12,8))
ax.plot(tem_dec_monthly_mean.index,
tem_dec_monthly_mean["Min"], color="k")
为了在 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())
但这给了我非常混乱的 x 轴刻度(所有日期从 1960 年到 2021 年),但我只想显示十二月的日子,因为这个数据集是十二月的。
有人可以指导我如何通过使用 Dateformatter
或任何其他方式获得我想要的格式
由于只排月日很难区分年份,所以我用YearLocator()
指定月日,然后格式化要竖排的行,3 -年间隔,以使其更易于阅读。添加网格使其更易于阅读。
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()