Matplotlib绘图及X轴日期格式化问题解决咨询
问题
尝试使用Python的Matplotlib库绘制时序图表,初始代码如下:
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(r'Plot_Example.csv',sep=';') df = df.set_index("Date") fig, ax = plt.subplots() fig.set_size_inches(18.5, 18.5) ax.plot(df["Yt"], label="Yt",color='blue') ax.plot(df["X1t"], label="X1t",color='red') ax.plot(df["X2t"],label="X2t",color='yellow') ax.legend() fig.savefig('test3png.png',dpi=100)
数据集信息:
df.info() <class 'pandas.core.frame.DataFrame'> Index: 96 entries, 1/1/1949 to 1/12/1956 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Yt 96 non-null int64 1 X1t 96 non-null int64 2 X2t 96 non-null int64 dtypes: int64(3) memory usage: 2.6+ KB
初始代码生成的图表数据显示正常,但X轴日期无法显示。添加日期格式化代码后,X轴格式正常,但Y轴数据显示异常,修改后代码如下:
import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import YearLocator, DateFormatter df = pd.read_csv(r'Plot_Example.csv',sep=';') df["Date"] = pd.to_datetime(df["Date"]) df = df.set_index("Date") fig, ax = plt.subplots() fig.set_size_inches(18.5, 18.5) ax.plot(df["Yt"], label="Yt",color='blue') ax.plot(df["X1t"],label="X1t",color='red') ax.plot(df["X2t"], label="X2t", color='yellow') years = mdates.YearLocator() yearsFmt = mdates.DateFormatter('\n%Y') ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.legend() fig.savefig('test3png.png', dpi=100)
需要解决原图表X轴日期显示问题,或修正修改后绘图异常的问题。
解决方案
问题根源
- 初始代码中
Date列未转为datetime类型,Matplotlib无法识别为日期轴,导致X轴日期不显示。 - 修改后的代码存在两个问题:一是错误使用未导入的
mdates别名(实际仅导入了YearLocator和DateFormatter),会引发运行报错;二是图表尺寸设置过大(18.5x18.5),导致Y轴显示比例严重失调。
修正方案
方案一:修复Matplotlib手动格式化代码
import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import YearLocator, DateFormatter # 读取数据并转换日期格式 df = pd.read_csv(r'Plot_Example.csv', sep=';') df["Date"] = pd.to_datetime(df["Date"]) df = df.set_index("Date") # 创建图表,使用合理尺寸 fig, ax = plt.subplots(figsize=(12, 6)) # 绘制时序曲线 ax.plot(df["Yt"], label="Yt", color='blue') ax.plot(df["X1t"], label="X1t", color='red') ax.plot(df["X2t"], label="X2t", color='yellow') # 设置X轴日期格式(直接使用导入的类,无需mdates别名) years = YearLocator() yearsFmt = DateFormatter('\n%Y') ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) # 添加必要标签和图例 ax.legend() ax.set_xlabel("日期") ax.set_ylabel("数值") # 保存并展示图表 fig.savefig('test3png.png', dpi=100) plt.show()
方案二:使用Pandas内置绘图简化操作
Pandas对时序数据的绘图支持更友好,可自动处理日期轴:
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv(r'Plot_Example.csv', sep=';') df["Date"] = pd.to_datetime(df["Date"]) df = df.set_index("Date") # Pandas自动识别日期轴,直接绘图 df.plot(figsize=(12, 6), color=['blue', 'red', 'yellow']) plt.legend(["Yt", "X1t", "X2t"]) plt.xlabel("日期") plt.ylabel("数值") plt.savefig('test3png.png', dpi=100) plt.show()
关键注意点
- 必须将
Date列转为datetime类型,这是正确识别日期轴的核心前提。 - 避免设置过大的图表尺寸,推荐使用
(12,6)这类常规比例,防止坐标轴显示失调。 - 导入模块时避免混用未定义的别名,直接使用导入的类或函数。
内容的提问来源于stack exchange,提问作者Andreas Zaras
相关产品推荐
相关产品推荐

