pangxie的个人博客分享 http://blog.sciencenet.cn/u/pangxie

博文

[转载]ggplot2箱线图加散点图

已有 6640 次阅读 2020-10-2 22:19 |个人分类:R语言|系统分类:科研笔记|文章来源:转载

rm(list = ls()) #清除工作区

library(ggplot2)

library(RColorBrewer)

###################################################

#导入数据

#使用并列箱线图叠加散点图表示四缸,六缸,八缸发动机对每加仑汽油行驶的英里数

#Group:为因子变量,表示汽车发动机的缸数

#Value:为连续变量,表示对每加仑汽油行驶的英里数

attach(mtcars)

Data1 = data.frame(Group = mtcars$cyl,Value = mtcars$mpg)
Data1$Group = factor(Data1$Group,levels = c(4,6,8))

###################################################

#离散数据的坐标轴中数据做为 factor 变量处理,他的位置取决于 level的顺序

#使用ggplot2包生成箱线图

windowsFonts(Times = windowsFont(family = "Times New Roman")) #Times New Roman字体         

P1 <- ggplot(Data1,aes(x=Group,y=Value,fill=Group))+ #”fill=“设置填充颜色

  stat_boxplot(geom = "errorbar",width=0.15,aes(color="black"))+ #由于自带的箱形图没有胡须末端没有短横线,使用误差条的方式补上

  geom_boxplot(size=0.5,fill="white",outlier.fill="white",outlier.color="white")+ #size设置箱线图的边框线和胡须的线宽度,fill设置填充颜色,outlier.fill和outlier.color设置异常点的属性

  scale_x_discrete(breaks=c("4","6","8"),

                   labels=c("4c","6c","8c")) +#设置x轴刻度标签

  geom_jitter(aes(fill=Group),width =0.2,shape = 21,size=2.5)+ #设置为向水平方向抖动的散点图,width指定了向水平方向抖动,不改变纵轴的值

  scale_fill_manual(values = c("#E69F00", "#0072B2","#F0E442"))+  #设置填充的颜色

  scale_color_manual(values=c("black","black","black"))+ #设置散点图的圆圈的颜色为黑色

  ggtitle("Car Milleage Data")+ #设置总的标题

  theme_bw()+ #背景变为白色

  theme(#legend.position="left", #不需要图例

        axis.text.x=element_text(colour="black",family="Times",size=14), #设置x轴刻度标签的字体属性

        axis.text.y=element_text(family="Times",size=14,face="plain"), #设置y轴刻度标签的字体属性

        axis.title.y=element_text(family="Times",size = 14,face="plain"), #设置y轴的标题的字体属性

        axis.title.x=element_text(family="heiti",size = 14,face="plain"), #设置x轴的标题的字体属性

        plot.title = element_text(family="Times",size=15,face="bold",hjust = 0.5), #设置总标题的字体属性

        panel.grid.major = element_blank(), #不显示网格线

        panel.grid.minor = element_blank())+

  ylab("Miles Per Gallon")+xlab("Number of Cylinders") #设置x轴和y轴的标题

P1

#图片保存

jpeg(file = "boxplot.jpg",width =1400,height = 1600,units = "px",res =300) #结果保存

print(P1)

dev.off()


本文链接:https://blog.csdn.net/zhouhucheng00/article/details/88764082




https://wap.sciencenet.cn/blog-3448646-1252992.html

上一篇:测抗氧化指标注意事项
下一篇:R语言计算spearman相关性
收藏 IP: 210.28.31.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

全部作者的其他最新博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-24 00:40

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部