2017-05-25 24 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