使用ggplot按组映射平均值

时间:2018-06-25 10:02:15

标签: r ggplot2

使用示例数据框:

Count

我希望按“长度”绘制每个组(波浪)的平均“值”(折线图)。

这可能直接来自ggplot吗? (或者我需要先做初步分析)。

否则我会使用:

 df <- structure(list(value = c(10L, 8L, 6L, 4L, 2L, 9L, 7L, 5L, 3L, 
    1L, 1L, 1L, 2L, 3L, 4L, 3L, 3L, 4L, 5L, 2L, 2L, 4L, 6L, 4L, 7L, 
    3L, 5L, 4L, 6L, 3L), length = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 
    4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 
    5L, 1L, 2L, 3L, 4L, 5L), wave = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 
    3L, 3L, 3L, 3L, 3L, 3L, 3L)), .Names = c("value", "length", "wave"
    ), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
    -30L), spec = structure(list(cols = structure(list(value = structure(list(), class = c("collector_integer", 
    "collector")), length = structure(list(), class = c("collector_integer", 
    "collector")), wave = structure(list(), class = c("collector_integer", 
    "collector"))), .Names = c("value", "length", "wave")), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"))

1 个答案:

答案 0 :(得分:1)

我们可以使用stat_summary来完成任务

library(ggplot2)
ggplot(df, aes(x = length, y = value, col = as.factor(wave))) + 
  stat_summary(geom = "line", fun.y = mean)

enter image description here