You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将NewCases与DailyVaccinations两个折线图合并为一张

解决方案

方法1:一次性选中多字段绘图(最简便)

pandas的DataFrame.plot.line()接口默认会将所有数值列自动绘制成同一画布下的独立折线,你只需要在筛选数据时把两个要展示的指标都选中即可:

df_merged.loc[df_merged['Country'] == 'The United Kingdom', 
              ['DateReported', 'NewCases', 'DailyVaccinations']]\
         .set_index('DateReported')\
         .plot.line(figsize=(10,6))

运行后会自动生成带图例的双折线图,不需要额外配置。

方法2:复用坐标轴对象(适合需要自定义每条线样式的场景)

如果你需要分别给两条折线设置颜色、标签、线型等属性,可以手动复用matplotlib坐标轴对象:

import matplotlib.pyplot as plt

# 绘制第一条线,拿到坐标轴对象ax
ax = df_merged.loc[df_merged['Country'] == 'The United Kingdom', 
                   ['DateReported', 'NewCases']]\
              .set_index('DateReported')\
              .plot.line(figsize=(10,6), color='red', label='新增确诊')

# 绘制第二条线时指定ax参数,即可在同一画布叠加
df_merged.loc[df_merged['Country'] == 'The United Kingdom', 
              ['DateReported', 'DailyVaccinations']]\
         .set_index('DateReported')\
         .plot.line(ax=ax, color='blue', label='每日疫苗接种量')

plt.show()

补充提示

如果两个字段数值差异过大,其中一条折线会被压缩得看不出趋势,可以给数值更大的字段设置secondary_y=True,生成双Y轴展示:

# 只需修改第二个绘图的参数即可
df_merged.loc[df_merged['Country'] == 'The United Kingdom', 
              ['DateReported', 'DailyVaccinations']]\
         .set_index('DateReported')\
         .plot.line(ax=ax, color='blue', label='每日疫苗接种量', secondary_y=True)

内容的提问来源于stack exchange,提问作者lyubol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:15:01