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

如何在ggplot2中绘制多折线图?示例数据下%_one与%_two的可视化需求

用ggplot2绘制百分比多折线图

步骤1:数据预处理

你的原始数据里,百分比列带%符号、日期是字符串格式,且为宽结构(每类百分比占一列)——而ggplot2更适配长结构数据,先做预处理:

首先加载必要工具包:

library(tidyverse)

输入示例数据(或用read.table/read.csv读取本地数据):

df <- tibble(
  Date = c("07-11-2022", "07-12-2022", "07-13-2022", "07-14-2022", "07-15-2022", "07-16-2022"),
  Total = c(368, 510, 544, 496, 320, 295),
  Count_1 = c(43, 56, 62, 77, 39, 33),
  `%_one` = c("11.7%", "11.0%", "11.4%", "15.5%", "12.2%", "11.2%"),
  Count_2 = c(132, 177, 187, 196, 118, 99),
  `%_two` = c("35.9%", "34.7%", "34.4%", "39.5%", "36.9%", "33.6%")
)

执行数据清洗与格式转换:

df_clean <- df %>%
  # 将字符串日期转为日期类型,确保x轴按时间排序
  mutate(Date = lubridate::mdy(Date)) %>%
  # 移除百分比符号并转为数值型
  mutate(across(c(`%_one`, `%_two`), ~ as.numeric(str_remove(., "%")))) %>%
  # 转成长结构:合并百分比列,用Type标记组别
  pivot_longer(cols = c(`%_one`, `%_two`), 
               names_to = "Type", 
               values_to = "Percentage") %>%
  # 给组别列设置更友好的名称
  mutate(Type = case_when(
    Type == "%_one" ~ "Group 1",
    Type == "%_two" ~ "Group 2"
  ))

步骤2:绘制多折线图

用ggplot2实现分组折线绘制,添加自定义样式:

ggplot(df_clean, aes(x = Date, y = Percentage, color = Type)) +
  # 绘制折线,可调整线条粗细
  geom_line(linewidth = 1.2) +
  # 可选:添加数据点,让趋势更直观
  geom_point(size = 3) +
  # 设置分组颜色,也可自定义颜色:scale_color_manual(values = c("#FF6B6B", "#4ECDC4"))
  scale_color_viridis_d(option = "plasma") +
  # 设置坐标轴与标题
  labs(
    x = "日期",
    y = "百分比 (%)",
    title = "两组百分比趋势对比",
    color = "分组"
  ) +
  # 使用简洁主题
  theme_minimal() +
  # 调整x轴日期文本角度,避免重叠
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

核心说明

  • 转长结构是关键:ggplot2的分组绘图依赖长数据,pivot_longer将多列百分比合并为一列,用Type区分组别,只需一次geom_line即可生成多条折线。
  • 日期转换:确保x轴按时间顺序排列,而非字符串排序。
  • 数值转换:百分比列必须转为数值型,才能在y轴显示连续刻度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:18:19