ggplot2如何画散点图拼接密度图

发布时间:2022-01-15 17:21:04 作者:柒染
来源:亿速云 阅读:285

ggplot2如何画散点图拼接密度图,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。


ggplot2如何画散点图拼接密度图  
image.png

前几天有一个读者在公众号留言问上面这幅图应该如何实现,我想到一个办法是利用ggplot2分别画散点图和密度图,然后利用aplot包来拼图,aplot包是ggtree的作者新开发的一个包,非常重要的一个作用就是解决拼图的时候坐标轴对齐的问题。这个aplot包的用法大家可以在微信搜索里直接搜aplot就可以直接找到原作者写的推文的介绍,而且这个公众号经常推送R语言的学习内容,非常好,作者是真正的大神级别的人物了。

 

aplot包:让你画出更复杂的图

好了下面就开始介绍具体的实现过程

 首先是模拟数据

生成两列符合正态分布的数据,然后组合成一个数据框

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()
 
ggplot2如何画散点图拼接密度图  
image.png

按照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()
 
ggplot2如何画散点图拼接密度图  
image.png

接下来是添加辅助线

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")
 
ggplot2如何画散点图拼接密度图  
image.png
 接下来是密度图
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())
 
ggplot2如何画散点图拼接密度图  
image.png

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如何画散点图拼接密度图  
image.png


看完上述内容,你们掌握ggplot2如何画散点图拼接密度图的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. python如何使用matplotlib画柱状图、散点图
  2. python中Seaborn怎么画散点图

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ggplot2

上一篇:circBank数据库有什么用

下一篇:springboot整合quartz定时任务框架的方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》