Continuous line across groups in ggplot

試著忘記壹切 提交于 2019-12-02 06:06:26

问题


I've got a timeseries of data where some of the data is observed and some of the data is simulated. I would like to generate a plot of the entire data series over time, with the color indicating the data source. However, I can only figure out how to make geom_line() in ggplot connect points in the same group.

Here's an example to clarify:

# Create sample data
df <- data.frame(cbind(seq(1,9,1), c(1,2,3,4,5,4,3,2,1), c("obs","obs", "obs", "obs", "sim","sim","obs","sim", "obs")))
colnames(df) <- c("time", "value", "source")

# Make a plot
p <- ggplot(df, aes(x=time, y=value, group=source, color=source))
p + geom_point()  # shows all the points in sequential order as dots
p + geom_point() + geom_line() # connects obs to obs and sim to sim

In this example, I would like a line to go sequentially from 1:9 on the x-axis, connecting all points, but change the color of the line (and points) based on the group.


回答1:


df <- data.frame(cbind(
                       seq(1,9,1), 
                       c(1,2,3,4,5,4,3,2,1), 
                       c("obs","obs","obs","obs","sim","sim","obs","sim","obs"),
                       c("all","all","all","all","all","all","all","all","all")))

colnames(df) <- c("time", "value", "source", "group")

ggplot(df,aes(x=time,y=value)) + 
    geom_point(aes(colour=source)) + 
    geom_path(data=df,aes(y=value,x=time,group=group,colour=source))




回答2:


If you only want a single line in geom_path, there is no need to actually create an additional column for your reference data. You can just force a single group by using any text string directly within the aes argument. For example:

df <- data.frame(time = 1:9, 
                 value = c(1:5, 4:1),
                 source = c("obs","obs","obs","obs","sim","sim","obs","sim","obs"))


ggplot(df,aes(x=time,y=value, colour=source)) + 
  geom_point() + 
  geom_path(aes(group="all"))



来源:https://stackoverflow.com/questions/20984793/continuous-line-across-groups-in-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!