Geom_line没有正确地为字符绘制颜色,但对于数字来说很好

时间:2016-02-02 23:51:26

标签: r colors ggplot2

我很困惑。说我有以下数据:

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))+
  geom_line()

enter image description here

但这有效(第2组的颜色会正确改变)?

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

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要在group=group函数中添加aes子句以获得您想要的内容,否则它无法正确处理这些因素:

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