Seaborn同画布绘制lineplot与countplot时仅显示countplot问题
问题原因
代码运行后折线不显示,是以下几个错误共同导致的:
- 缺失必要依赖导入:没有引入
matplotlib.pyplot和matplotlib.ticker模块,运行时会直接抛出名称错误 - 字段名不匹配:传入lineplot的x轴字段
Year、y轴字段Val和实际数据集列名Treaty Year、As of Combined Incurred Amount完全不一致,seaborn找不到对应字段,无法生成折线 - 无效冗余代码:
ax1 = sns.set_style(style=None, rc=None )属于错误写法,sns.set_style是全局样式配置方法,没有返回值,这行只会给ax1赋值空值;且直接用原始数据集绘制折线时,同一年份对应多条金额记录,折线会出现杂乱的多点重叠,需要先按年份聚合金额 - 图层逻辑问题:未设置图层优先级时,后绘制的countplot柱形会完全覆盖底层折线,且双轴未做区分,可读性差
修正后可直接运行的代码
%matplotlib inline import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker import seaborn as sns matplotlib.rc_file_defaults() sns.set_style(style=None, rc=None) # 加载测试数据集 df = pd.DataFrame([ [1999, 69512.0], [2001, 552564.63], [2001, 1955896.62], [2004, 976349.81], [2013, 787644.0], [2013, 26937.63], [1999, 95510.0], [1999, 1670073.53], [1999, 1752561.23], [1999, 222182.81] ], columns=['Treaty Year', 'As of Combined Incurred Amount']) # 按年份聚合累计理赔金额,用于折线图展示 year_agg = df.groupby('Treaty Year', as_index=False)['As of Combined Incurred Amount'].sum() fig, ax1 = plt.subplots(figsize=(12, 6)) # 左轴绘制countplot(年度保单数量),设置半透明放在底层 sns.countplot(x='Treaty Year', data=df, ax=ax1, zorder=1, alpha=0.5, color='#2c7fb8') ax1.set_ylabel('年度保单数量', color='#2c7fb8') ax1.tick_params(axis='y', labelcolor='#2c7fb8') # 创建右双轴绘制lineplot(年度累计理赔额),放在上层 ax2 = ax1.twinx() sns.lineplot(x='Treaty Year', y='As of Combined Incurred Amount', data=year_agg, marker='o', sort=True, ax=ax2, zorder=2, color='#d95f02', linewidth=2.5) ax2.set_ylabel('年度累计理赔金额', color='#d95f02') ax2.tick_params(axis='y', labelcolor='#d95f02') # 金额轴添加千分位格式化 ax2.get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda x, p: format(int(x), ','))) plt.tight_layout() plt.show()
实现效果说明
- 左Y轴对应半透明蓝色柱形,统计每个年份的保单条目数
- 右Y轴对应橙色折线,展示每个年份的累计理赔金额
- 通过zorder参数明确图层顺序,搭配半透明设置,两类图表不会互相遮挡,双轴颜色和标签对应,可读性符合预期
内容的提问来源于stack exchange,提问作者Luke Bernstein
相关产品推荐
相关产品推荐

