使用pyplot与Seaborn在同图绘制多条折线失败求助
咱们先拆解你遇到的两个核心问题,再给出针对性的解决方案:
一、Matplotlib Pyplot的问题:空白图表+图例错误
你用plt.plot()时错误地使用了x=和y=关键字参数,但Matplotlib的plot()函数不支持这种写法——它的前两个参数是位置参数,直接传入x、y数据即可,不需要加参数标签。这就导致你的代码根本没把数据传递给绘图函数,所以图表空白;同时因为没有实际生成带标签的线条,自然找不到可用于生成图例的元素,触发No handles with labels found to put in legend错误。
修正后的Pyplot代码
import matplotlib.pyplot as plt # 提前提取各年份数据,让代码更清晰 df_2016 = df3.query('year == 2016') df_2017 = df3.query('year == 2017') df_2018 = df3.query('year == 2018') df_2019 = df3.query('year == 2019') # 直接传递x、y数据,去掉多余的关键字参数 plt.plot(df_2016['month'], df_2016['Total_Revenue'], label='2016 : Total Revenue', color='red') plt.plot(df_2017['month'], df_2017['Total_Revenue'], label='2017 : Total Revenue', color='blue') plt.plot(df_2018['month'], df_2018['Total_Revenue'], label='2018 : Total Revenue', color='orange') plt.plot(df_2019['month'], df_2019['Total_Revenue'], label='2019 : Total Revenue', color='green') # 完善图表元素 plt.legend() plt.xlabel('Month') plt.ylabel('Total Revenue') plt.title('Annual Monthly Total Revenue') plt.show()
二、Seaborn的问题:生成多个独立子图
你误用了seaborn.lmplot()——这个函数是用来绘制线性回归拟合图的,而且每次调用都会创建一个新的FacetGrid(即新图表),所以四次调用就生成了四个独立子图。如果想用Seaborn绘制折线图,应该用seaborn.lineplot(),它支持在同一个坐标轴上绘制多条分组折线。
更简洁的Seaborn解决方案
不需要手动拆分数据,直接用hue参数按年份自动分组绘制:
import seaborn as sns import matplotlib.pyplot as plt # 设置绘图风格 sns.set_style('darkgrid') # lineplot自动按year分组,生成不同颜色的折线 sns.lineplot(data=df3, x='month', y='Total_Revenue', hue='year', marker='o') # 完善图例和标签 plt.legend(title='Year', labels=['2016', '2017', '2018', '2019']) plt.xlabel('Month') plt.ylabel('Total Revenue') plt.title('Annual Monthly Total Revenue') plt.show()
这个方法更高效,Seaborn会自动处理年份分组和颜色区分,同时你的数据中2018年缺2月、2019年只有1-2月的情况,图表会自动跳过缺失值,不影响整体展示。
补充:关于图例错误的解释
No handles with labels found to put in legend的意思是:绘图库找不到任何带有label属性的绘图元素(比如线条、散点)来生成图例。在你的Pyplot代码中,因为参数传递错误没生成线条;在Seaborn代码中,lmplot的legend参数不接受字符串标签(它只控制是否显示图例),且每次生成新图,最后调用plt.legend()时当前轴没有带标签的元素,所以报错。
内容的提问来源于stack exchange,提问作者user8270077

