Вопрос

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.

Это было полезно?

Решение

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))

enter image description here

Другие советы

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"))

enter image description here

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top