使用多行添加两条平滑线

时间:2018-04-29 21:47:46

标签: r ggplot2

我有一个由多行组成的基础图,我想在ggplot2中使用平滑线重新创建。

数据如下所示:

x1
   ID            P    col   Lat
   86230 0.16666667  black 45.06
   86230 0.57142857  black 45.42
   86230 0.88235294  black 45.66
   86230 1.00000000  black 45.87
   96464 0.46428571  black 45.06
   96464 0.50000000  black 45.42
   96464 0.92857143  black 45.66
   96464 1.00000000  black 45.87
   97181 0.94736842 gray87 45.06
   97181 0.87500000 gray87 45.42
   97181 0.82352941 gray87 45.66
   97181 0.33333333 gray87 45.87
  101351 0.40000000  black 45.06
  101351 1.00000000  black 45.42
  101351 1.00000000  black 45.66
  101351 1.00000000  black 45.87
  102193 0.15789474  black 45.06
  102193 0.66666667  black 45.42
  102193 0.96875000  black 45.66
  102193 1.00000000  black 45.87
  102156 0.94736842 gray87 45.06
  102156 1.00000000 gray87 45.42
  102156 0.82142857 gray87 45.66
  102156 0.10000000 gray87 45.87

代码:

plot(x1$Lat[1:4], x1$P[1:4], col="black", 
     type = "b", lwd = 3,
     xlab = "Latitude", xaxt = 'n',cex.lab=1.25,
     ylab = "Frequency",
     pch = 8, cex = 1.0, main = "Transect B", ylim = c(0:1))

for (j in 1:548)
  points(x1$Lat[(j*4)+1:4], x1$P[(j*4)+1:4], 
         col=tolower(x1$col[(j*4)+1]),
         type = "b", lwd = 3, pch = 8, cex = 1)

axis(1, x1$Lat)

获取此图表: enter image description here 我想将具有正趋势的所有黑线平滑成一条线,将灰线平滑成另一条平滑线。

使用其他帖子的建议,我尝试过:

x1 <- x1[1:548,2:4] ##dont ID
x1<- tbl_df(x1)

x1 <- x1 %>% gather(key, Value, -Lat)
pl <- ggplot(x1, aes(x = Lat, y = P, col = key)) + geom_line() + 
  geom_smooth(method = lm) + theme_classic()

p2 <- ggplot(x1, aes(x = Lat, y = P, col = col)) + geom_line() + 
                   geom_smooth(method = lm) + theme_classic()

我确信这是一个简单的解决方案。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以使用geom_smooth制作摘要行。诀窍是如何对数据进行分组。在geom_line中,您希望按ID分组,因此每个ID都有自己的行。在geom_smooth中,您希望按颜色分组,以便获得一条线来表示每种颜色的所有ID。您可以使用alpha,线型和线条大小来区分各个线条和分组线条;我使用alpha&amp; linetype来做到这一点。

library(tidyverse)

ggplot(df, aes(x = Lat, y = P)) +
        geom_line(aes(group = ID, color = col), alpha = 0.6) +
        geom_smooth(aes(color = col), method = lm, linetype = 2, se = F, show.legend = F) +
        scale_color_identity() +
        theme_light()

reprex package(v0.2.0)创建于2018-04-29。

相关问题