2015-10-23 29 views
2

我試圖與直方圖一個簡單的小刻面2×1在GGPLOT2與GGPLOT2

data <- read.csv("/hist_distances.csv", check.names = FALSE, sep = ",") 

mdata <- melt(data) 

m <- ggplot(data, aes(x=Distance)) 
m + geom_histogram() 

頭(數據)

給出:

 Times Distance 
1 3.093060 260.8840 
2 2.557780 187.4960 
3 0.263611 10.6584 
4 2.880000 184.5970 
5 5.035000 281.3490 
6 6.952780 251.4730 

頭(mdata)

給出:

variable value 
1 Times 3.093060 
2 Times 2.557780 
3 Times 0.263611 
4 Times 2.880000 
5 Times 5.035000 
6 Times 6.952780 

尾(MDATA)

給出:

 variable value 
1739 Distance 1.103670 
1740 Distance 1.695610 
1741 Distance 3.795020 
1742 Distance 6.651960 
1743 Distance 0.719843 
1744 Distance 6.504050 

這產生這樣的圖形: enter image description here

我曾嘗試:

m <- ggplot(mdata, aes(x=value)) + 
geom_histogram() + 
m + facet_wrap(~ variable) 

沒有成功。

我怎樣才能生成一個多面的圖形,而不是頂部的變量「次」的直方圖和底部的變量「距離」的直方圖?

+0

你見過[facet_wrap(http://docs.ggplot2.org/0.9.3.1/facet_wrap.html)?嘗試'facet_wrap(〜變量)'在你的情況。 – David

+0

哎呀,是的,我更新了問題 – Rodolphe

+2

'facet_wrap(〜variable)'不適合你,因爲它會產生1x2而不是2x1圖?使用'facet_grid(variable〜。)'而不是'facet_wrap'會產生一個2x1圖。 – David

回答

3

使用facet_grid(variable ~ .),其中facet_grid(行〜列):

df <- data.frame(Time = rnorm(100), 
       Distance = rnorm(100) 
       ) 
dfm <- melt(df) 

ggplot(dfm, aes(x=value)) + geom_histogram() + facet_grid(variable ~ .) 

編輯跟進評論: 如果你的數據在不同的尺度,使用facet_grid(variable ~ ., scales = "free")

有關選項,請參見help(facet_grid)

enter image description here

+0

太好了,謝謝!現在我的數據範圍從一個變量到另一個變量是不同的。距離範圍從0到600,時間從0到10.有沒有辦法調整x尺度?請讓我知道你是否想讓我再問一個問題。乾杯! – Rodolphe

+1

使用'facet_wrap(〜variable,scales =「free_x」)''。如果你想在一列中繪製圖,使用'facet_wrap(〜variable,scales =「free_x」,ncol = 1)',並排使用'facet_wrap(〜variable,scales =「free_x」,ncol = 2 )'。 – eipi10