how can I make a line between each data in one subfigure

时间:2018-01-23 19:12:49

标签: r

My data is like this

 df<- structure(list(time = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
    3L, 3L), .Label = c("5", "1", "2"), class = "factor"), key = c("boy1", 
    "boy2", "boy3", "boy1", "boy2", "boy3", "boy1", "boy2", "boy3"
    ), x = c("1", "2", "3", "1", "2", "3", "1", "2", "3"), y = c(177.72258835, 
    0, 74.438539625, 134.3410045, 48915.1, 38.302204425, 97.32286187, 
    25865.25, 28.67291878), sd = c(58.852340736, 0, 21.291893740908, 
    42.92051958201, 72521.52726, 16.309811239722, 32.40355615268, 
    38347.81965, 10.34204226254)), .Names = c("time", "key", "x", 
    "y", "sd"), class = "data.frame", row.names = c(NA, -9L))

I plot it like this

ggplot(df, aes(x, y, col = key)) +
  geom_point() +
  scale_x_discrete(labels=c("first", "second", "third"), limits = c(1, 2,3)) +
  facet_grid(time ~ .) +
  geom_errorbar(aes(ymin = y-sd, ymax = y+sd)) +
  facet_grid(time ~ ., scale = "free_y")

I want to connect the three data in each time together by line

I used this http://www.cookbook-r.com/Graphs/Bar_and_line_graphs_(ggplot2)/ when I use geom_line() I get error

ggplot(df, aes(x, y, col = key)) +
  geom_line() +
  geom_point() +
  scale_x_discrete(labels=c("first", "second", "third"), limits = c(1, 2,3)) +
  facet_grid(time ~ .) +
  geom_errorbar(aes(ymin = y-sd, ymax = y+sd)) +
  facet_grid(time ~ ., scale = "free_y") 

the error is like this

geom_path: Each group consists of only one observation. Do you need to adjust the
group aesthetic?
geom_path: Each group consists of only one observation. Do you need to adjust the
group aesthetic?
geom_path: Each group consists of only one observation. Do you need to adjust the
group aesthetic?

1 个答案:

答案 0 :(得分:0)

You're having trouble because you map color globally, and different colors implies different lines. So, in the geom_line() layer we pick a color and we explicitly set a group (as the messages suggested), which tells ggplot2 which points should be connected. In this case, we want all the points connected (within a facet), so we just set group to a single value.

ggplot(df, aes(x, y, col = key)) +
  geom_point() +
  geom_line(color = "black", group = 1) +
  scale_x_discrete(labels=c("first", "second", "third"), limits = c(1, 2,3)) +
  facet_grid(time ~ .) +
  geom_errorbar(aes(ymin = y-sd, ymax = y+sd)) +
  facet_grid(time ~ ., scale = "free_y")

enter image description here