Imlerith
Imlerith

Reputation: 489

plot variation of variable with time using ggplot2 in R

I have the following example data:

my.list <- vector('list',1000)
for(i in 1:1000)
{
    temp <- sample(c("type1","type2"),1)
    my.list[[i]] <- data.frame(time=i,type=temp)
}
df <- do.call('rbind',my.list)

I want to plot the variation of the type variable with time. I used the following:

ggplot(df,aes(x=time,y=type)) + geom_line()

with this command, I am not getting the expected result:

enter image description here

Notice how a transition from type 1 to type 2 and vice versa doesn't show in the plot. Did I miss something ?

Plus, in this plot, it seems that at time x, the type variable takes both type1 and type2 as values which is contradictory to the data frame's contents

Upvotes: 0

Views: 587

Answers (1)

Martin C. Arnold
Martin C. Arnold

Reputation: 9678

For this two work, you have to use the group argument.

ggplot(df,aes(x=time,y=type, group=1)) + geom_line()

Note, however, that the result will be hard to interpret since the lines are quite dense when using 1000 observations. If you use only 100 observations, so

set.seed(1)
my.list <- vector('list',100)
for(i in 1:100)
{
  temp <- sample(c("type1","type2"),1)
  my.list[[i]] <- data.frame(time=i,type=temp)
}
df <- do.call('rbind',my.list)

the result looks as follows:

enter image description here

Upvotes: 2

Related Questions