【R语言】堆叠折线图绘制大揭秘

1. 图像绘制

👋📚📌 之前绘制过相关的图,但是时间一久就不知道把代码放到哪里去了,索性重新写一个绘图代码,用以记录,需要的自取。

library(readxl)
library(ggplot2)
library(dplyr)
# setwd("D:/Datasets/GD/sample result") #修改文件路径
# data <- read_excel("dataset.xlsx", sheet = 2) # 替换成你的文件

# 随机生成数据框,用于绘图
data <- data.frame(
  Type = sample(c(1, 2, 4, 5), 100, replace = TRUE),
  A = runif(100, 0.5, 1),
  B = runif(100, 0.5, 1),
  C = sample(0:30, 100, replace = TRUE)
)
data$Type <- as.factor(data$Type)
summary(data)

data_summary <- data %>%
  group_by(C, Type) %>%
  summarise(mean_A = mean(A, na.rm = TRUE), .groups = 'drop')
head(data_summary)
str(data_summary)

# 重新定义自定义颜色向量和标签
custom_colors <- c("1" = "#1f77b4", "2" = "#ff7f0e", "4" = "#2ca02c", "5" = "#d62728")
custom_labels <- c("1" = "A", "2" = "B", "4" = "C", "5" = "D")

ggplot(data_summary, aes(x = C, y = mean_A, color = Type, group = Type)) +
  geom_line(linetype = "solid", size = 1.2) +
  geom_hline(yintercept = 0.7, linetype = "dashed", color = "red", size = 0.8) +  # 添加红色虚线
  scale_x_continuous(limits = c(0, 30), breaks = seq(0, 30, by = 5)) +
  scale_y_continuous(limits = c(0.5, 1.0), breaks = seq(0.5, 1.0, by = 0.05)) +
  scale_color_manual(values = custom_colors, labels = custom_labels) +  # 自定义颜色和标签
  labs(x = "C", y = "mean A", color = "Types") +
  theme_minimal(base_size = 14, base_family = "serif") +
  theme(
    axis.title.x = element_text(size = 14, face = "bold"),
    axis.title.y = element_text(size = 14, face = "bold", angle = 90),
    axis.text.x = element_text(size = 12, color = "black"),
    axis.text.y = element_text(size = 12, color = "black"),
    legend.title = element_text(size = 14, face = "bold"),
    legend.text = element_text(size = 12),
    legend.position = "top",
    legend.direction = "horizontal",
    legend.box = "horizontal",
    panel.border = element_rect(color = "black", size = 1, fill = NA),
    panel.grid.major = element_line(color = "grey80", size = 0.5),  # 设置主网格线
    panel.grid.minor = element_line(color = "grey90", size = 0.25),  # 设置次网格线
    panel.background = element_rect(fill = "grey95", color = NA)  # 设置背景颜色
  )
  

结果展示:
在这里插入图片描述

  希望这个分享对大家有所帮助,如果你有任何问题,欢迎在评论区留言交流!一起进步,一起成长! 🌟

2. 参考文档

# 第一种:
base + theme(legend.position = "right") 

# 第二种:
labelled +
  theme(
    legend.position = c(0, 1),
    legend.justification = c(0, 1))

# 不显示图例
labelled + theme(legend.position = "none")

  1. 不显示图例,theme(legend.position = “none”);
  2. 第一种方法属于theme主题系统,元素名legend.position,引号内可选参数有right、left、bottom,对应右、下、左
  3. 第二种方法,元素legend.position和legend.justification同时出现并且值相同,想象图例在坐标轴里,则c(0, 1)为面板左上角,c(1, 0)为面板右下角,c(0.5, 0,5)为面板中间;面板指绘图区域。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jackson的生态模型

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值