2017-05-25 49 views
0

我有不对齐以下两部分积:对齐侧由端相关曲线与GGPLOT2

enter image description here

Side-by-side plots not aligned

这些图是通过以下代码制作:

require(ggplot2) 
require(gridExtra) 

set.seed(0) 
data <- data.frame(x=rpois(30,5),y=rpois(30,11),z=rpois(300,25)) 
left.plot <- ggplot(data,aes(x,y)) 
       + geom_bin2d(binwidth=1) 

margin.data <- as.data.frame(margin.table(table(data),1)) 
right.plot <- ggplot(margin.data, aes(x=x,y=Freq)) 
       + geom_bar(stat="identity")+coord_flip()               

grid.arrange(left.plot, right.plot, ncol=2) 

如何将左侧图中的行与右侧图中的条对齐?

回答

0

您的问题很简单,尽管双重。

最终,您需要使用scale_y_continuous()scale_x_continuous()来设置您的坐标轴限制以匹配坐标图。这受到价值因素所阻碍。将它转换为数字,并进行一些缩放,并且您很好。

left.plot <- ggplot(data,aes(x,y)) + 
    geom_bin2d(binwidth=1) + 
    scale_y_continuous(limits = c(1, 16)) 

margin.data <- as.data.frame(margin.table(table(data),1)) 
right.plot <- ggplot(margin.data, aes(x=as.numeric(as.character(x)),y=Freq)) + 
    geom_bar(stat="identity") + 
    scale_x_continuous(limits = c(1, 16)) + 
    xlab("x") + 
    coord_flip() 

enter image description here

+0

我不明白,为什么在右图您的解决方案中有4级或更小,而在左边有3条只有在标记低于4 –

+0

它看起来像我们的随机数据不同;尝试对您的机器进行调整,并确认您的左右数字对齐。让我知道如果他们不。 – Nancy

+0

不,他们不对齐。在你的身影中看到它。左边的绘图在右边的绘图中没有数值为3的数据。看到我上面的答案。 –

0

使用包ggExtra我能得到一个几乎解决方案

require(ggplot2) 
require(ggExtra) 

set.seed(0) 
data <- data.frame(x=rpois(30,5),y=rpois(30,11),z=rpois(300,25)) 
left.plot <- ggplot(data,aes(x,y)) + geom_bin2d(binwidth=1) 

ggMarginal(left.plot, margins="y", type = "histogram", size=2,bins=(max(data$y)-min(data$y)+1),binwidth=1.06)  

我说差不多,因为我不得不手动binwidth = 1.06设置为对准酒吧和计数。

Manually aligned plots using ggExtra::ggMarginal