您能否将边缘密度的轴与散点图的轴对齐

时间:2016-05-27 17:54:18

标签: r

嗨,我有下面的图,边缘密度图稍微偏离。它们不与散点图的x轴和y轴对齐,因此解释可能有点误导。

我可以尝试使用这些代码行来尝试获得边距以对齐边缘图,但这非常手动且令人沮丧。

theme0(plot.margin = unit(c(1,0,0,2.2),"lines"))
theme0(plot.margin = unit(c(0,1,1.2,0),"lines"))

有没有办法自动找到合适的边距传递给theme0(plot.margin = unit(c(0,1,1.2,0),"lines"),这样就不需要手动工作来排列边距了?谢谢。

library(ggplot2)
library(gridExtra)

set.seed(42)
DF <- data.frame(x=rnorm(100,mean=c(1,5)),y=rlnorm(100,meanlog=c(8,6)),group=1:2)
DF

## Scatter plot
p1 <- ggplot(DF,aes(x=x,y=y)) + geom_point() +
  scale_x_continuous(expand=c(0.02,0)) +
  scale_y_continuous(expand=c(0.02,0)) +
  theme_bw() +
  theme(legend.position="none",plot.margin=unit(c(0,0,0,0),"points")) # ggplot(DF,aes(x=x,y=y,colour=factor(group))) color the gorup

theme0 <- function(...) theme( legend.position = "none",
                               panel.background = element_blank(),
                               panel.grid.major = element_blank(),
                               panel.grid.minor = element_blank(),
                               panel.margin = unit(0,"null"),
                               axis.ticks = element_blank(),
                               axis.text.x = element_blank(),
                               axis.text.y = element_blank(),
                               axis.title.x = element_blank(),
                               axis.title.y = element_blank(),
                               axis.ticks.length = unit(0,"null"),
                               axis.ticks.margin = unit(0,"null"),
                               panel.border=element_rect(color=NA),...)
### DENSITY OF X
p2 <- ggplot(DF,aes(x=x, fill="blue")) + 
  geom_density(alpha=0.5) + 
  scale_x_continuous(breaks=NULL,expand=c(0.02,0)) +
  scale_y_continuous(breaks=NULL,expand=c(0.02,0)) +
  theme_bw() +
  theme0(plot.margin = unit(c(1,0,0,2.2),"lines"))  # to color group   ggplot(DF,aes(x=x,colour=factor(group),fill=factor(group)))

### DENSITY OF Y
p3 <- ggplot(DF,aes(x=y, fill = "red")) + 
  geom_density(alpha=0.5) + 
  coord_flip()  + 
  scale_x_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
  scale_y_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
  theme_bw() +
  theme0(plot.margin = unit(c(0,1,1.2,0),"lines"))  # color group  ggplot(DF,aes(x=y,colour=factor(group),fill=factor(group)))

grid.arrange(arrangeGrob(p2,ncol=2,widths=c(3,1)),
             arrangeGrob(p1,p3,ncol=2,widths=c(3,1)),
             heights=c(1,3))

0 个答案:

没有答案