Python:忽略年份按月日绘制多个DataFrame数据
解决按月份日期忽略年份绘制多年份DataFrame数据的问题
我来帮你搞定这个绘图问题!你当前的代码直接用原始的datetime索引绘图,因为每个DataFrame的年份不同,Matplotlib会把它们按真实的时间顺序排列(2017年的数据在最左侧,2018年在中间,2019年在右侧),自然没法实现“忽略年份只按月日对比”的需求。这里有两种可靠的解决方案:
方法一:统一替换索引年份(推荐)
把所有日期的年份替换成同一个虚拟年份(比如选闰年2020,避免2月29日的日期报错),这样所有数据都会对齐到同一个时间轴上,完美实现同月同日的数据对比:
import matplotlib.pyplot as plt # 遍历你的DataFrame列表its for df in its: # 将每个日期的年份替换为2020,生成新的索引 adjusted_dates = df.index.map(lambda dt: dt.replace(year=2020)) # 绘图时添加年份标签,方便区分不同年份的数据 plt.plot(adjusted_dates, df['Crocs'], label=f"Year {df.index.year[0]}") # 美化图表 plt.xlabel("Month-Day") plt.ylabel("Crocs Value") plt.title("Crocs Data Comparison (Ignoring Year)") plt.legend() plt.show()
这种方法的优势是保留了datetime类型的时间顺序,x轴会自动按正确的月日顺序排列,不会出现字符串排序的问题。
方法二:转换为月日字符串索引
如果你更倾向于用字符串形式的月日作为x轴,可以把索引转换成%m-%d格式的字符串:
import matplotlib.pyplot as plt for df in its: # 将datetime索引转换为"MM-DD"格式的字符串 month_day_labels = df.index.strftime("%m-%d") plt.plot(month_day_labels, df['Crocs'], label=f"Year {df.index.year[0]}") # 旋转x轴标签避免重叠 plt.xticks(rotation=45) plt.xlabel("Month-Day") plt.ylabel("Crocs Value") plt.title("Crocs Data Comparison (Ignoring Year)") plt.legend() plt.show()
注意:如果你的数据日期不是严格按周递增的,字符串索引的排序可能会出现小问题,所以更推荐第一种方法。
内容的提问来源于stack exchange,提问作者Ijaz Ur Rahim
相关产品推荐
相关产品推荐

