👋📚📌 之前绘制过相关的图,但是时间一久就不知道把代码放到哪里去了,索性重新写一个绘图代码,用以记录,需要的自取。
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) # 设置背景颜色
)
结果展示:
希望这个分享对大家有所帮助,如果你有任何问题,欢迎在评论区留言交流!一起进步,一起成长! 🌟