使用plot()绘制DateTime对象时,如何指定X轴显示的年份?
问题描述
使用代码plt.plot(df['Date'], df['Price'])绘制折线图时,df['Date']为包含多年数据的DateTime对象,df['Price']是整数类型,但生成的折线图X轴会自动间隔较大地显示约4个年份,如何指定X轴显示的年份数量,或是仅显示所有年份(仅年份值)?
示例代码
数据生成代码
import pandas as pd import datetime import random dates = [] prices = [] for count in range(10000): prices.append(random.randint(0, 10)) dates.append(datetime.datetime(random.randint(1960, 2022), random.randint(1, 12), random.randint(1, 27)).strftime("%Y-%m-%d")) data = { 'Date': dates, 'Price': prices } df = pd.DataFrame(data) df = df.sort_values(by=['Date'], ignore_index=True) df_temp = df.copy() df_temp['Date DT'] = pd.to_datetime(df_temp['Date']) df_temp = df_temp.drop(axis='columns', columns='Date') df = df_temp
初始绘图代码
import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import figure plt.figure(figsize=(15, 5), dpi=1000) plt.plot(df['Date DT'], df['Price']) # Labels plt.xlabel('Dates', fontsize=8) plt.ylabel('Prices', fontsize=8) # Save plt.title('Example', fontsize=15) plt.savefig('example.png', bbox_inches='tight')
解决方法
一、指定X轴显示的年份数量
借助matplotlib.dates模块的YearLocator控制年份间隔,用DateFormatter设置仅显示年份的格式:
import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import YearLocator, DateFormatter plt.figure(figsize=(15, 5), dpi=1000) plt.plot(df['Date DT'], df['Price']) # 设置X轴年份间隔:每隔5年显示一个刻度(可修改数字调整间隔) year_locator = YearLocator(5) plt.gca().xaxis.set_major_locator(year_locator) # 设置刻度仅显示年份 plt.gca().xaxis.set_major_formatter(DateFormatter('%Y')) # Labels plt.xlabel('Dates', fontsize=8) plt.ylabel('Prices', fontsize=8) # Save plt.title('Example', fontsize=15) plt.savefig('example.png', bbox_inches='tight') plt.show()
二、显示所有存在数据的年份
提取数据中所有唯一的年份,手动设置X轴刻度和标签:
import numpy as np import matplotlib.pyplot as plt import pandas as pd plt.figure(figsize=(15, 5), dpi=1000) plt.plot(df['Date DT'], df['Price']) # 提取所有唯一年份 unique_years = df['Date DT'].dt.year.unique() # 将年份转换为当年1月1日的datetime对象,作为刻度位置 year_ticks = [pd.to_datetime(f'{year}-01-01') for year in unique_years] # 设置X轴刻度和标签 plt.gca().set_xticks(year_ticks) plt.gca().set_xticklabels(unique_years, fontsize=8) # 旋转X轴标签避免重叠 plt.xticks(rotation=45) # Labels plt.xlabel('Dates', fontsize=8) plt.ylabel('Prices', fontsize=8) # Save plt.title('Example', fontsize=15) plt.savefig('example.png', bbox_inches='tight') plt.show()
内容的提问来源于stack exchange,提问作者Jiehfeng
相关产品推荐
相关产品推荐

