2016-09-12 53 views
0

我正在構建水柱的垂直剖面圖。我的問題是,這些點連接在x個觀測值上,而不是y個觀測值。在ggplot下,我知道geom_path可以做到這一點,但我不能使用ggplot,因爲我想添加幾個x軸。因此我使用plot()。 因此,這裏是我的嘗試:r plot中的垂直剖面()

Storfjorden <- read.delim("C:/Users/carvi/Desktop/Storfjorden.txt") 
smooF=smooth.spline(Storfjorden$Fluorescence,Storfjorden$Depth,spar=0.50) 
plot(Storfjorden$Fluorescence,Storfjorden$Depth,ylim=c(80,0),type="n") 
lines(smooF) 

Resulting plot

正如你看到的,這些點是通過X觀察連接。但要觀察垂直剖面,我希望看到它們通過y觀測進行連接。我試着按順序排列它們(使用order())並且它不影響結果。任何人都有線索?

如果,作爲替代方案,有人將有一個想法如何在單個情節(溫度,鹽度,熒光)繪製不同的線路具有不同的軸,然後我可以使用geom_path()。謝謝!

**我有你可能會回答的一個新興問題,ggplot中有一種方法可以生成geom_smooth(),但觀察連接的順序是它們出現而不是x軸?

ggplot(melteddf,aes(y=Depth,x=value))+geom_path()+facet_wrap 
+(~variable,nrow=1,scales="free‌​_x")+scale_y_reverse‌​() 
+geom_smooth(span=‌​0.5,se=FALSE) 

我試過使用smooth.spline,但沒有認出geom_path中的對象。謝謝!

回答

0

還有一個原因,ggplot2使得它很難繪製在一個圖多個x軸 - 它通常會導致難以閱讀(或者更糟,誤導)圖。如果你有爲什麼你例子落入其中的一個類別,它可能使我們能夠幫助您更瞭解詳細內容,一個激勵的例子。但是,下面兩種解決方法可能有所幫助。

下面是一個快速MWE來解決這個問題 - 如果您給我們看起來像您的實際數據的東西,可能會更有幫助,但這至少可以獲得非常不同的比例(儘管沒有結構,情節相當混亂)。

請注意,我正在使用dplyr進行多次操作,並將reshape2melt的數據轉換爲長格式以便於繪圖。

library(dplyr) 
library(reshape2) 

df <- 
    data.frame(
    depth = runif(20, 0, 100) %>% round %>% sort 
    , measureA = rnorm(20, 10, 3) 
    , measureB = rnorm(20, 50, 10) 
    , measureC = rnorm(20, 1000, 30) 
) 


meltedDF <- 
    df %>% 
    melt(id.vars = "depth") 

第一種選擇是簡單地使用面積彼此相鄰的數據:

meltedDF %>% 
    ggplot(aes(y = depth 
      , x = value)) + 
    geom_path() + 
    facet_wrap(~variable 
      , nrow = 1 
      , scales = "free_x") + 
    scale_y_reverse() 

enter image description here

第二是標準化數據,然後繪製這一點。在這裏,我使用z-score,但如果你有理由使用別的東西(例如縮放到中心的任何變量,你正在使用),你可以改變配方的「適當」量:

meltedDF %>% 
    group_by(variable) %>% 
    mutate(Standardized = (value - mean(value))/sd(value) ) %>% 
    ggplot(aes(y = depth 
      , x = Standardized 
      , col = variable)) + 
    geom_path() + 
    scale_y_reverse() 

enter image description here

如果需要繪製多個站點,這裏是網站的一些樣本數據:

df <- 
    data.frame(
    depth = runif(60, 0, 100) %>% round %>% sort 
    , measureA = rnorm(60, 10, 3) 
    , measureB = rnorm(60, 50, 10) 
    , measureC = rnorm(60, 1000, 30) 
    , site = sample(LETTERS[1:3], 60, TRUE) 
) 


meltedDF <- 
    df %>% 
    melt(id.vars = c("site", "depth")) 

您可以使用facet_grid(我的偏好):

meltedDF %>% 
    ggplot(aes(y = depth 
      , x = value)) + 
    geom_path() + 
    facet_grid(site~variable 
      , scales = "free_x") + 
    scale_y_reverse() 

enter image description here

或添加facet_wrap到標準化的情節:

meltedDF %>% 
    ggplot(aes(y = depth 
      , x = value)) + 
    geom_path() + 
    facet_grid(site~variable 
      , scales = "free_x") + 
    scale_y_reverse() 

enter image description here