简体   繁体   中英

Draw line between points with groups in ggplot

I have a time-series, with each point having a time, a value and a group he's part of. I am trying to plot it with time on x axis and value on y axes with the line appearing a different color depending on the group.

I tried using geom_path and geom_line , but they end up linking points to points within groups. I found out that when I use a continuous variable for the groups, I have a normal line; however when I use a factor or a categorical variable, I have the link problem.

Here is a reproducible example that is what I would like:

df = data.frame(time = c(1,2,3,4,5,6,7,8,9,10), value = c(5,4,9,3,8,2,5,8,7,1), group = c(1,2,2,2,1,1,2,2,2,2))
ggplot(df, aes(time, value, color = group)) + geom_line()

图表应该是什么样子的图像

And here is a reproducible example that is what I have:

df = data.frame(time = c(1,2,3,4,5,6,7,8,9,10), value = c(5,4,9,3,8,2,5,8,7,1), group = c("apple","pear","pear","pear","apple","apple","pear","pear","pear","pear"))
ggplot(df, aes(time, value, color = group)) + geom_line()

图形实际外观的图像

So the first example works well, but 1/ it adds a few lines to change the legend to have the labels I want, 2/ out of curiosity I would like to know if I missed something.

Is there any option in ggplot I could use to have the behavior I expect, or is it an internal constraint?

As pointed by Richard Telford and Carles Sans Fuentes , adding group = 1 within the ggplot aesthetic makes the job. So the normal code should be:

ggplot(df, aes(time, value, color = group, group = 1)) + geom_line()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM