其他
R可视化——ggplot2中组合图的绘制(主图中插入小图)
rm(list=ls())#clear Global Environment
setwd('D:\\桌面\\绘图技巧')#设置工作路径
#安装包
# install.packages("ggplot2")
# install.packages("ggprism")
# install.packages("ggpubr")
#加载包
library(ggplot2)
library(ggprism)
library(ggpubr)
#加载数据(以R自带数据mtcars为例)
data(mtcars)
df <- mtcars[, c("mpg","cyl","wt")]
#将cyl转换为因子型
df$cyl <- as.factor(df$cyl)
#小图绘制箱线图
p1 <- ggplot(df,aes(x=cyl,y=wt))+#指定数据
stat_boxplot(geom = "errorbar", width=0.1,size=0.8)+#添加误差线,注意位置,放到最后则这条先不会被箱体覆盖
geom_boxplot(aes(fill=cyl), #绘制箱线图函数
outlier.colour="white",size=0.8)+#异常点去除
geom_jitter(width = 0.2)+#添加抖动点
geom_signif(comparisons = list(c("4","6"),
c("6","8"),
c("4","8")),# 设置需要比较的组
map_signif_level = T, #是否使用星号显示
test = t.test, ##计算方法
y_position = c(5,5.5,6),#图中横线位置设置
tip_length = c(c(0.01,0.01),
c(0.01,0.01),
c(0.01,0.01)),#横线下方的竖线设置
size=0.8,color="black")+
theme_prism(palette = "candy_bright",
base_fontface = "plain", # 字体样式,可选 bold, plain, italic
base_family = "serif", # 字体格式,可选 serif, sans, mono, Arial等
base_size = 16, # 图形的字体大小
base_line_size = 0.8, # 坐标轴的粗细
axis_text_angle = 45)+ # 可选值有 0,45,90,270
scale_fill_prism(palette = "candy_bright")+
theme(panel.background =element_blank(), #背景
axis.line=element_line(),#坐标轴的线设为显示
plot.title = element_text(size=14))#图例位置
p1
p2 <- ggplot(df,aes(mpg,wt))+
geom_point(shape=21,color=df$cyl,fill=df$cyl)+
geom_smooth(method="lm",
color="#034C76",fill="grey",size=1)+#添加拟合线
theme_prism(palette = "flames",
base_fontface = "plain",
base_family = "serif",
base_size = 16,
base_line_size = 0.8,
axis_text_angle = 45)+
scale_fill_prism(palette = "candy_bright")+#填充色
labs(title = "散点图", # 定义主标题
subtitle = "XXXXXXX", # 定义子标题
x = "XXXXX", # 定义x轴文本
y = "XXXXX")# 定义y轴文本
p2
#通过ggplot2包的函数annotation_custom()将箱线图作为小图插入到主图中
p2 + annotation_custom(grob=ggplotGrob(p1),ymin = 3.2, ymax = 5.8, xmin=22, xmax=35)
好看你就
点点
我