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

Matplotlib绘制新冠死亡率趋势图时如何添加国家均值水平线

直接在你现有的遍历国家的循环逻辑中,调用Matplotlib坐标轴对象的axhline方法即可实现需求,该方法会自动生成横跨整个绘图区域的水平参考线。

你可以将原有的遍历国家代码块修改为如下内容:

for country in list(colors.keys()):
    row = covid.iloc[-1]
    # 提前计算当前国家的死亡率均值,避免重复计算
    country_mean = covid[country].mean()
    # 新增:绘制均值水平参考线
    plot.axhline(
        y=country_mean,
        color=colors[country],
        linestyle='--',
        alpha=0.6,
        linewidth=3
    )
    plot.text(x = covid.index[-1], y = row[country], color = colors[country], s = country, weight = 'bold')
    plot.text(x = covid.index[-1], y = country_mean, color = colors[country], s = 'Mean for ' + country + ": " + str(round(country_mean,2)), weight = 'bold')

参数说明

  • y:指定水平参考线的纵向位置,直接传入对应国家的死亡率均值即可
  • color:复用你预先定义的对应国家配色,和趋势线颜色统一,识别更直观
  • linestyle:设为虚线--,和实线的原始趋势线做区分
  • alpha:降低透明度避免遮挡原有趋势线数据
  • linewidth:按需调整参考线粗细,示例值3既醒目又不会干扰主趋势线展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:45:03