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

如何使用R语言ggplot2包将指定多组数据绘制为单张图表

使用ggplot2绘制多组数据到同一张图表

首先,先把你提供的表格数据整理成R可识别的格式,先构造宽格式数据,再转换为ggplot2更适用的长格式数据(这是ggplot2处理多组数据的关键)。

步骤1:构造并转换数据

根据你提供的图片数据,先创建数据框,再用tidyr::pivot_longer转换为长格式:

# 加载需要的包
library(ggplot2)
library(tidyr)

# 构造宽格式数据
df <- data.frame(
  x = 1:5,
  y1 = c(0.00, 0.22, 0.32, 0.39, 0.44),
  y2 = c(0.00, 0.15, 0.22, 0.27, 0.31),
  y3 = c(0.00, 0.10, 0.16, 0.20, 0.23),
  y4 = c(0.00, 0.07, 0.12, 0.15, 0.17),
  y5 = c(0.00, 0.05, 0.09, 0.11, 0.13)
)

# 转换为长格式
df_long <- pivot_longer(df, cols = starts_with("y"), names_to = "group", values_to = "value")

步骤2:绘制多组折线图(带点)

这是展示多组趋势数据最常用的方式,用geom_line搭配geom_point:

ggplot(df_long, aes(x = x, y = value, color = group, group = group)) +
  geom_line(linewidth = 1) +  # 设置线条粗细
  geom_point(size = 2) +      # 设置点大小
  labs(
    x = "X轴",
    y = "Y轴数值",
    title = "多组数据对比图",
    color = "数据组"
  ) +
  theme_minimal()  # 选用简洁主题,也可以替换为theme_bw()等其他主题

其他可选展示方式

  • 仅展示散点图:
ggplot(df_long, aes(x = x, y = value, color = group)) +
  geom_point(size = 3) +
  labs(x = "X轴", y = "Y轴数值", color = "数据组") +
  theme_bw()
  • 并列柱状图:
ggplot(df_long, aes(x = x, y = value, fill = group)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  labs(x = "X轴", y = "Y轴数值", fill = "数据组") +
  theme_bw()

内容的提问来源于stack exchange,提问作者Kazi Fayzus Salahin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:40:50