[英]Scatterplot with left and bottom histograms in ggplot2
像下面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翻转为图片?
以此为起点:
grid.arrange(hist_left, scatter, empty, hist_bottom,
widths=c(1, 4), as.table=FALSE, nrow=2)
您还应该删除空白占位符图中的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
转换hist_left' to a grob with
editGrob`的grob并使用视口参数(例如,但请注意,这不是您想要的)来获取准确的图像:
hlg <- ggplotGrob(hist_left)
hlg <- editGrob(hlg, vp=viewport(angle=90))
但您需要重新整理网格图形,以弄清楚如何操作grob表组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.