如何在ggplot中创建error_bar类型的图表

时间:2016-02-12 18:32:43

标签: r ggplot2

dput(df)        

structure(list(Client = structure(c(1L, 2L, 3L, 3L, 3L, 3L, 4L, 
    4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 1L, 2L, 3L, 
    3L, 3L, 3L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 
    7L), .Label = c("AAA", "BBB", "CCC", "DD", "FF", "GG", "KK"), class = "factor"), 
        Date = structure(c(-715126, -715126, -715126, -715126, -715126, 
        -715126, -715126, -715126, -715126, -715126, -715126, -715126, 
        -715126, -715126, -715126, -715126, -715126, -715126, -715126, 
        -715126, -715066, -715066, -715066, -715066, -715066, -715066, 
        -715066, -715066, -715066, -715066, -715066, -715066, -715066, 
        -715066, -715066, -715066, -715066, -715066, -715066, -715066
        ), class = "Date"), time = structure(c(0.701550925925926, 
        0.706759259259259, 0.714988425925926, 0.715162037037037, 
        0.719293981481481, 0.761006944444444, 0.719351851851852, 
        0.729166666666667, 0.720648148148148, 0.720648148148148, 
        0.720648148148148, 0.720648148148148, 0.720648148148148, 
        0.720648148148148, 0.73662037037037, 0.720648148148148, 0.720648148148148, 
        0.762789351851852, 0.721122685185185, 0.762789351851852, 
        0.705023148148148, 0.748425925925926, 0.722627314814815, 
        0.715162037037037, 0.719293981481481, 0.771423611111111, 
        0.722824074074074, 0.743055555555556, 0.726203703703704, 
        0.720648148148148, 0.720648148148148, 0.720648148148148, 
        0.720648148148148, 0.720648148148148, 0.740092592592593, 
        0.720648148148148, 0.720648148148148, 0.762789351851852, 
        0.721122685185185, 0.762789351851852), format = "h:m:s", class = "times")), .Names = c("Client", 
    "Date", "time"), row.names = c(NA, -40L), class = "data.frame")

我需要能够使用ggplot创建geom_error类型图表,其中ymin是给定日期中最早的时间,ymax是给定日期的最新时间。

我试过这个:

ggplot() + 
  geom_errorbar(data=subset(df, Client %in% c("CCC")), mapping=aes(x=Date, ymin=min(time), ymax=max(time), width=0.2, size=2, color="blue")) + 
  geom_point(data=subset(df, Client %in% c("CCC")), mapping=aes(x=Date, y=mean(time)), size=1, shape=21, fill="white")

似乎不起作用。我没有像图表中预期的那样得到酒吧。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

I hope I understood what you are trying to achieve: Here I used stat_summary() to calculate the mean value for the points and the min and max values for the errorbars.

  ggplot(data=subset(df, Client %in% c("CCC")), aes(x=Date, y=time)) + 
  stat_summary(fun.ymin = min, fun.ymax = max, geom="errorbar", width=0.2, size=2, color="blue") +
  stat_summary(fun.y = "mean", geom="point", size=1, shape=21, fill="white")