2016-09-12 51 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