如何使用左下角直方图创建散点图,就像下面ggplot2中的示例一样?
library(ggplot2)
library(gridExtra)
data1<-diamonds
detrend<-lm(log(price)~log(carat),data=data1)
data1$lprice2<-resid(detrend)
empty <- ggplot()+geom_point(aes(1,1), colour="white")+
opts(axis.ticks=theme_blank(),
panel.background=theme_blank(),
axis.text.x=theme_blank(), axis.text.y=theme_blank(),
axis.title.x=theme_blank(), axis.title.y=theme_blank())
scatter<-qplot(log(carat),lprice2,data=data1,xlab="Weight",ylab="Price Residuals",
colour=factor(color),main="Diamonds - Weight to Price by Color")
scatter<-scatter+theme(legend.position="top")
scatter<-scatter+theme(plot.title=element_text(size=20,colour="blue"))
hist_left<-ggplot(data1,aes(x=price, fill=color))+geom_histogram(aes(y = ..density..))+
theme(legend.position = "none")+coord_flip()
hist_bottom<-ggplot(data1,aes(x=carat, fill=color))+geom_histogram()
+theme(legend.position = "none")
如何使用grid.arrange来排列这些图以及如何像图片那样翻转hist_left?
答案 0 :(得分:0)
以此为出发点:
grid.arrange(hist_left, scatter, empty, hist_bottom,
widths=c(1, 4), as.table=FALSE, nrow=2)
答案 1 :(得分:0)
您还应该删除空白占位符图中的panel.grid
并切换到element_blank
vs theme_blank
。另外,请删除hist_left
上的标签。
library(ggplot2)
library(gridExtra)
data1 <- diamonds
detrend <- lm(log(price)~log(carat) ,data=data1)
data1$lprice2 <- resid(detrend)
empty <- ggplot()
empty <- empty + geom_point(aes(1,1), colour="white")
empty <- empty + 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(),
panel.grid=element_blank())
scatter <- qplot(log(carat), lprice2, data=data1,
xlab="Weight", ylab="Price Residuals",
colour=factor(color),
main="Diamonds - Weight to Price by Color")
scatter <- scatter + theme(legend.position="top")
scatter <- scatter + theme(plot.title=element_text(size=20, colour="blue"))
hist_left <- ggplot(data1,aes(x=price, fill=color))
hist_left <- hist_left + geom_histogram(aes(y = ..density..))
hist_left <- hist_left + labs(x=NULL, y=NULL, title=NULL)
hist_left <- hist_left + theme(legend.position = "none")
hist_bottom <- ggplot(data1, aes(x=carat, fill=color))
hist_bottom <- hist_bottom + geom_histogram()
hist_bottom <- hist_bottom + theme(legend.position = "none")
grid.arrange(arrangeGrob(hist_left + coord_flip(), scatter, ncol=2, widths=c(1,3)),
arrangeGrob(empty, hist_bottom, ncol=2, widths=c(1,3)),
heights=c(3,1))
您可以通过scale_x_reverse
来接近目标:
grid.arrange(arrangeGrob(hist_left + scale_x_reverse(), scatter, ncol=2, widths=c(1,3)),
arrangeGrob(empty, hist_bottom, ncol=2, widths=c(1,3)),
heights=c(3,1))
并且,您可以尝试通过转换hist_left' to a grob with
editGrob`并使用视口参数来获取您的确切图像(例如,但请注意,这不是您想要的):
hlg <- ggplotGrob(hist_left)
hlg <- editGrob(hlg, vp=viewport(angle=90))
但是你需要刷新网格图形来弄清楚你想如何操作grob表组件。