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

使用matplotlib在折线图上叠加绘制散点图的代码实现咨询

实现代码说明

你已经绘制完折线图后,在调用plt.show()前执行plt.scatter()即可直接叠加散点,matplotlib默认在当前激活的画布上叠加新图层。

完整代码示例

import matplotlib.pyplot as plt
import pandas as pd

# ---------------------- 你原有绘制折线图的代码(示例) ----------------------
# 示例数据:1-12月的平均、最低、最高气温,替换为你自己的实际数据即可
months = range(1,13)
mean_temp = [2,4,10,16,22,26,28,27,22,15,8,3]
min_temp = [-3,-1,4,9,15,20,22,21,16,8,2,-2]
max_temp = [7,10,16,23,28,31,33,32,28,22,14,8]

plt.plot(months, mean_temp, label='时段内月均温', color='#1f77b4')
plt.plot(months, min_temp, label='时段内月最低温', color='#2ca02c')
plt.plot(months, max_temp, label='时段内月最高温', color='#ff7f0e')

# ---------------------- 叠加散点的核心代码 ----------------------
# 假设你准备好的散点dataframe名为scatter_df,包含两列:
# month:对应记录的月份(1-12,和x轴刻度取值一致)
# monthly_avg:对应记录的月平均气温值
plt.scatter(
    x = scatter_df['month'],
    y = scatter_df['monthly_avg'],
    s = 12, # 散点大小,可调整
    c = '#d62728', # 散点颜色,避免和折线撞色
    alpha = 0.5, # 透明度,点多重叠时调低
    label = '1837-2020历史月均温记录'
)

# ---------------------- 统一美化输出(你原有代码也可保留) ----------------------
plt.xlabel('月份')
plt.ylabel('气温(℃)')
plt.xticks(months, labels=['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'])
plt.legend()
plt.show()

常见调整说明

  • 如果你x轴用的是字符串格式的月份(如['1月','2月'...]),只需保证scatter_df['month']的取值和x轴刻度格式完全一致即可
  • 如果你用的是matplotlib面向对象写法(预先定义了fig, ax = plt.subplots()),把代码中的plt.scatter替换为ax.scatter即可,参数完全不变
  • 散点的颜色、大小、透明度可根据实际显示效果自由调整,数据量大会重叠的话建议把alpha设为0.3-0.6区间的数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:54:04