为了账号安全,请及时绑定邮箱和手机立即绑定

在ggplot2中使用边缘直方图的散点图

在ggplot2中使用边缘直方图的散点图

Smart猫小萌 2019-08-29 09:07:46
在ggplot2中使用边缘直方图的散点图有没有办法用边缘直方图创建散点图,就像下面的示例一样ggplot2?在Matlab中它是scatterhist()函数,并且R也存在等价物。但是,我还没有看到ggplot2。我开始尝试创建单个图形,但不知道如何正确排列它们。 require(ggplot2)  x<-rnorm(300)  y<-rt(300,df=2)  xy<-data.frame(x,y)      xhist <- qplot(x, geom="histogram") + scale_x_continuous(limits=c(min(x),max(x))) + opts(axis.text.x = theme_blank(), axis.title.x=theme_blank(), axis.ticks = theme_blank(), aspect.ratio = 5/16, axis.text.y = theme_blank(), axis.title.y=theme_blank(), background.colour="white")      yhist <- qplot(y, geom="histogram") + coord_flip() + opts(background.fill = "white", background.color ="black")      yhist <- yhist + scale_x_continuous(limits=c(min(x),max(x))) + opts(axis.text.x = theme_blank(), axis.title.x=theme_blank(), axis.ticks = theme_blank(), aspect.ratio = 16/5, axis.text.y = theme_blank(), axis.title.y=theme_blank() )      scatter <- qplot(x,y, data=xy)  + scale_x_continuous(limits=c(min(x),max(x))) + scale_y_continuous(limits=c(min(y),max(y)))none <- qplot(x,y, data=xy) + geom_blank()并使用此处发布的功能安排它们。但长话短说:有没有办法创建这些图表?
查看完整描述

3 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

gridExtra包应该在这里工作。首先制作每个ggplot对象:

hist_top <- ggplot()+geom_histogram(aes(rnorm(100)))empty <- ggplot()+geom_point(aes(1,1), colour="white")+
         theme(axis.ticks=element_blank(), 
               panel.background=element_blank(), 
               axis.text.x=element_blank(), axis.text.y=element_blank(),           
               axis.title.x=element_blank(), axis.title.y=element_blank())scatter <- ggplot()+geom_point(aes(rnorm(100), rnorm(100)))hist_right <- ggplot()+geom_histogram(aes(rnorm(100)))+coord_flip()

然后使用grid.arrange函数:

grid.arrange(hist_top, empty, scatter, hist_right, ncol=2, nrow=2, widths=c(4, 1), heights=c(1, 4))


查看完整回答
反对 回复 2019-08-29
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

这不是一个完全响应的答案,但它非常简单。它说明了显示边际密度的另一种方法,以及如何将alpha级别用于支持透明度的图形输出:

scatter <- qplot(x,y, data=xy)  + 
         scale_x_continuous(limits=c(min(x),max(x))) + 
         scale_y_continuous(limits=c(min(y),max(y))) + 
         geom_rug(col=rgb(.5,0,0,alpha=.2))scatter


查看完整回答
反对 回复 2019-08-29
?
德玛西亚99

TA贡献1770条经验 获得超3个赞

这可能有点晚了,但我决定为此创建一个package(ggExtra),因为它涉及一些代码并且编写起来可能很乏味。该软件包还试图解决一些常见问题,例如确保即使有标题或文本被放大,这些图仍将是彼此内联的。

基本思想类似于这里给出的答案,但它有点超出了这个范围。以下是如何将边缘直方图添加到1000个点的随机集中的示例。希望这可以使将来更容易添加直方图/密度图。

链接到ggExtra包

library(ggplot2)df <- data.frame(x = rnorm(1000, 50, 10), y = rnorm(1000, 50, 10))p <- ggplot(df, aes(x, y)) + geom_point() + theme_classic()ggExtra::ggMarginal(p, type = "histogram")


查看完整回答
反对 回复 2019-08-29
  • 3 回答
  • 0 关注
  • 901 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信