【问题标题】:How to plot lines for the count data in R?如何为 R 中的计数数据绘制线条?
【发布时间】:2016-05-19 07:15:13
【问题描述】:

我有这样的数据框:

frame <- data.frame("AGE" = seq(18,44,1), 
                   "GROUP1"= c(83,101,159,185,212,276,330,293,330,356,370,325,264,274,214,229,227,154,132,121,83,69,57,32,16,17,8),
                   "GROUP2"= c(144,210,259,329,391,421,453,358,338,318,270,258,207,186,173,135,106,92,74,56,41,31,25,13,16,5,8))

我想在 X 轴上绘制 AGE,在 Y 轴上绘制 GROUP1 和 GROUP2 的值,在同一个图中用不同的颜色绘制。并且这些值应该由一条平滑的线连接起来。

作为第一部分,我融化了数据框并绘制了:

melt <- melt(frame, id.vars = "AGE")
melt <- melt[order(melt$AGE),]
plot(melt$AGE, melt$value)

【问题讨论】:

    标签: r


    【解决方案1】:

    这是使用dplyrtidyr 包的替代解决方案。

    library(dplyr)
    library(tidyr)
    
    newframe <- frame %>% gather("variable","value",-AGE)
    
    ggplot(newframe, aes(x=AGE, y=value, color=variable)) +
      geom_point() +
      geom_smooth()
    

    您可以使用geom_line() 来获取点之间的线,但在这里使用geom_smooth() 感觉更好。 geom_area 在线条下方为您提供阴影区域,但我们需要将 color 更改为 fill

    ggplot(newframe, aes(x=AGE, y=value, fill=variable)) + geom_area()
    

    【讨论】:

      【解决方案2】:

      我们可以使用matplot

      matplot(`row.names<-`(as.matrix(frame[-1]), frame[,1]), 
          ylab='value',type = "l", xlab = "AGE",col = c("red", "blue"), pch = 1)
      legend("topright", inset = .05, legend = c("GROUP1", "GROUP2"), 
              pch = 1, col = c("red", "blue"), horiz = TRUE)
      

      【讨论】:

      • 谢谢!是否可以用颜色遮住线条下方的区域?
      • @technOslerphile 有可能,但这不是最初的问题
      【解决方案3】:

      试试,

      library(ggplot2)
      ggplot(meltdf,aes(x=AGE,y=value,colour=variable,group=variable)) + geom_line()
      

      【讨论】:

        猜你喜欢
        • 2011-12-16
        • 1970-01-01
        • 2015-09-28
        • 2021-01-07
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        • 2021-07-29
        相关资源
        最近更新 更多