在ggplot2中使用邊緣直方圖的散點圖有沒有辦法用邊緣直方圖創(chuàng)建散點圖,就像下面的示例一樣ggplot2?在Matlab中它是scatterhist()函數(shù),并且R也存在等價物。但是,我還沒有看到ggplot2。我開始嘗試創(chuàng)建單個圖形,但不知道如何正確排列它們。 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()并使用此處發(fā)布的功能安排它們。但長話短說:有沒有辦法創(chuàng)建這些圖表?
3 回答

拉丁的傳說
TA貢獻1789條經(jīng)驗 獲得超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函數(shù):
grid.arrange(hist_top, empty, scatter, hist_right, ncol=2, nrow=2, widths=c(4, 1), heights=c(1, 4))

慕桂英3389331
TA貢獻2036條經(jīng)驗 獲得超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

德瑪西亞99
TA貢獻1770條經(jīng)驗 獲得超3個贊
這可能有點晚了,但我決定為此創(chuàng)建一個package(ggExtra
),因為它涉及一些代碼并且編寫起來可能很乏味。該軟件包還試圖解決一些常見問題,例如確保即使有標題或文本被放大,這些圖仍將是彼此內(nèi)聯(lián)的。
基本思想類似于這里給出的答案,但它有點超出了這個范圍。以下是如何將邊緣直方圖添加到1000個點的隨機集中的示例。希望這可以使將來更容易添加直方圖/密度圖。
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")
- 3 回答
- 0 關注
- 988 瀏覽
添加回答
舉報
0/150
提交
取消