【问题标题】:adding two smooth lines based using multiple lines使用多条线添加两条平滑线
【发布时间】:2018-04-29 21:47:46
【问题描述】:

我有一个由多条线组成的基础绘图图,我想使用平滑线在 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)

获取此图表: 我想将所有具有积极趋势的黑线平滑成一条线,将灰线平滑成另一条平滑线。

使用来自不同帖子的建议,我尝试过:

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()

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用geom_smooth 来制作摘要行。诀窍在于如何对数据进行分组。在geom_line 中,您想按 ID 分组,因此每个 ID 都有自己的行。在geom_smooth 中,您希望按颜色分组,以便得到一条线来表示每种颜色的所有 ID。您可以乱用 alpha、线型和线号来区分单独的线和分组的线;我使用 alpha 和 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 年 4 月 29 日创建。

    【讨论】:

    • 谢谢!这更多是关于我正在寻找的内容:pl &lt;- ggplot(df, aes(x = Lat, y = P)) pl + geom_smooth(aes(color = col), method = "auto", stat = "smooth") + theme_classic()
    猜你喜欢
    • 2022-01-17
    • 2011-08-12
    • 2016-03-25
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多