ggplot2如何画散点图拼接密度图,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
前几天有一个读者在公众号留言问上面这幅图应该如何实现,我想到一个办法是利用ggplot2分别画散点图和密度图,然后利用aplot包来拼图,aplot包是ggtree的作者新开发的一个包,非常重要的一个作用就是解决拼图的时候坐标轴对齐的问题。这个aplot包的用法大家可以在微信搜索里直接搜aplot就可以直接找到原作者写的推文的介绍,而且这个公众号经常推送R语言的学习内容,非常好,作者是真正的大神级别的人物了。
好了下面就开始介绍具体的实现过程
生成两列符合正态分布的数据,然后组合成一个数据框
x<-rnorm(500,0,1)y<-rnorm(500,0,2)df<-data.frame(x=x,y=y)head(df)
先做一个简单的散点图
library(ggplot2)ggplot(df,aes(x=x,y=y))+ geom_point()
按照Y轴的范围填充三个颜色,比如大于3填充一个,小于-3填充另外一种,-3到3中间的填充另外一种
给数据添加一列新的用来映射颜色
df$color<-ifelse(df$y>3,"A", ifelse(df$y<(-3),"B","D"))head(df)
画图
ggplot(df,aes(x,y))+ geom_point(aes(color=color))+ scale_color_manual(values=c("green","blue","grey"))+ theme_bw()
接下来是添加辅助线
ggplot(df,aes(x,y))+ geom_point(aes(color=color))+ scale_color_manual(values=c("green","blue","grey"))+ theme_bw()+ geom_hline(yintercept = -3,lty="dashed")+ geom_hline(yintercept = 3,lty="dashed")+ geom_vline(xintercept = -2,lty="dashed")
ggplot(df,aes(x))+ geom_density(fill="grey",alpha=0.5)+ scale_y_continuous(expand = c(0,0))+ theme_minimal()+ theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank())
y轴的密度分布也是这样画,下面就不重复了
library(ggplot2)library(aplot)p1<-ggplot(df,aes(x,y))+ geom_point(aes(color=color))+ scale_color_manual(values=c("green","blue","grey"))+ theme_bw()+ geom_hline(yintercept = -3,lty="dashed")+ geom_hline(yintercept = 3,lty="dashed")+ geom_vline(xintercept = -2,lty="dashed")p2<-ggplot(df,aes(x))+ geom_density(fill="grey",alpha=0.5)+ scale_y_continuous(expand = c(0,0))+ theme_minimal()+ theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank())p3<-ggplot(df,aes(y))+ geom_density(fill="grey",alpha=0.5)+ scale_y_continuous(expand = c(0,0))+ theme_minimal()+ theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank())+ coord_flip()p1%>% insert_top(p2,height = 0.5)%>% insert_right(p3,0.5)
看完上述内容,你们掌握ggplot2如何画散点图拼接密度图的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4579431/blog/4761052