LeslieKish
LeslieKish

Reputation: 434

Geom_line not plotting colors correctly for characters but fine for numerics

I'm confused. Say I have the following data:

require("ggplot2")

treatment=c(rep("NO", 10), rep("YES", 30), c(rep("NO", 10)),
            rep("YES", 10), rep("NO", 30), c(rep("YES", 10)))

dat=data.frame(time=rep(1:50, 2), group=rep(c("GROUP 1", "GROUP 2"),     each=50), treatment=treatment)

Why does this not work:

ggplot(dat, aes(x=time, y=group, color=treatment))+
  geom_line()

enter image description here

But this works (group 2's colors change correctly)?

ggplot(dat, aes(x=time, y=group, color=as.numeric(as.factor(treatment))))+
  geom_line()

enter image description here

Upvotes: 2

Views: 321

Answers (1)

Mike Wise
Mike Wise

Reputation: 22827

You need to add a group=group clause to the aes function to get what you want, othewise it doesn't handle the factors correctly:

require("ggplot2")

treatment=c(rep("NO", 10), rep("YES", 30), c(rep("NO", 10)),
            rep("YES", 10), rep("NO", 30), c(rep("YES", 10)))

dat=data.frame(time=rep(1:50, 2), group=rep(c("GROUP 1", "GROUP 2")
                                            each=50), treatment=treatment)


ggplot(dat, aes(x=time, y=group, color=treatment,group=group))+  
  geom_line()+ labs(title="Group")

enter image description here

Upvotes: 1

Related Questions