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

如何用Matplotlib拆分坐标数组并绘制散点图与折线图

使用Matplotlib绘制散点图与折线图(同画布)

完整代码实现

import matplotlib.pyplot as plt

# 定义数据集
data = {
    "category": "cat1",
    "Plot_val": [[1, 1.5, 2, 2, 3, 3.5, 4], [12, 15, 20, 25, 20, 30, 40]],
    "Line1_val": [[1, 2, 3, 4], [10, 20, 30, 40]],
    "Line2_val": [[1, 2, 3, 4], [20, 30, 40, 50]]
}

# 拆分各系列的x、y坐标
plot_x, plot_y = data["Plot_val"]
line1_x, line1_y = data["Line1_val"]
line2_x, line2_y = data["Line2_val"]

# 创建画布
plt.figure(figsize=(8, 6))

# 绘制Plot_val散点图
plt.scatter(plot_x, plot_y, color='crimson', marker='o', label='Plot_val')

# 绘制Line1_val折线图
plt.plot(line1_x, line1_y, color='darkblue', linestyle='-', marker='s', label='Line1_val')

# 绘制Line2_val折线图
plt.plot(line2_x, line2_y, color='forestgreen', linestyle='--', marker='^', label='Line2_val')

# 添加图表组件
plt.title('Combined Scatter & Line Chart')
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.legend()
plt.grid(True, alpha=0.3)

# 展示图表
plt.show()

关键说明

  • 数据拆分:直接从字典中提取每个列的x、y数组,简化绘图时的参数传递。
  • 样式区分:散点图用红色圆点,折线图分别用蓝色实线方形标记、绿色虚线三角标记,避免视觉混淆。
  • 可读性优化:添加标题、坐标轴标签、图例和半透明网格,让图表信息更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:47:14