title: “[R语言] ggplot2作图模板”
date: 2021-03-15
lastmod: 2021-03-15
draft: false
tags: [“R语言”,“ggplot2”]
categories: [“R语言”,“ggplot2”]
autoCollapseToc: true
多个时间点的折线图
# 创建示例数据
# 例如 "ID" "Group" "Time1" "Time2" "Time3"
data=data.frame(ID=paste0("A",c(1:100)),
Group=rep(letters[1:4],each=25), #4个分组
Time1=rnorm(n = 100,mean = 10,sd = 3) ,
Time2=rnorm(n = 100,mean = 15.5,sd = 7),
Time3=rnorm(n = 100,mean = 7.2,sd = 5)
)
# 长宽数据转化
data2=tidyr::pivot_longer(data, cols = 3:5,
names_to ="Time", values_to = "value")
# 正态性检测
tapply(data2$value,data2$Group,shapiro.test)
# 计算均数和标准差
data3_mean=tapply(data2$value,list(data2$Group,data2$Time),mean)
data3_sd=tapply(data2$value,list(data2$Group,data2$Time),sd)
data3 <- as.data.frame(data3_mean)
data3=tibble::rownames_to_column(data3,var="Group")
data4=pivot_longer(data3, cols = 2:4,
names_to ="Time", values_to = "value")
data3_2 <- as.data.frame(data3_sd)
data3_2=tibble::rownames_to_column(data3_2,var="Group")
data4_2=pivot_longer(data3_2, cols = 2:4,
names_to ="Time", values_to = "sd")
data4=merge(data4,data4_2,all = TRUE)
# [作图]
p1=ggplot(data4, mapping = aes(x = Time, y = value,
color=Group,fill=Group)) +
geom_point()+ xlab("xx")+ylab("xxx")+
geom_line(aes(group=Group))+
theme_bw()+theme(legend.position="right",);p1
#加误差线
data4$lowSD=data4$value-data4$sd
data4$highSD=data4$value+data4$sd
p2=p1+geom_errorbar(data=data4,
aes(y=value, ymin=lowSD, ymax=highSD,group=Group),
width=0.2);p2
#移除网格线 (但不移除背景颜色和边界线)
#+theme(panel.grid.major=element_blank(),panel.grid.minor=element_blank())
# [导图参数]
ggsave(paste0("图1.png"), p1, width=420, height=352, units="mm")
#
#library("eoffice")
#topptx(p1,filename = "mtcars.pptx")