ggplot中的颜色(geom_segment)

时间:2016-03-14 11:02:45

标签: r ggplot2

如何使用facet_grid时根据数据中的因子对geom_segments进行着色?我的方法失败了,因为颜色的分配是错误的。

以下是一些数据:

visual_data=data.frame(Values = 10:1, Words = c("yeah","what","is","up","and","how", "are", "things","for", "you"), group = c("a","b","a","b","a","b","a","b","a","b"), importance=c("#EF2A2A","#EF2A2A", "#E4FA11", "#E4FA11", "#E4FA11", "#E4FA11","#EF2A2A","#EF2A2A","#EF2A2A", "#E4FA11"))

此代码创建一个图:

graphic=ggplot(visual_data, aes(xend=Values, x=0, y=reorder(Words, Values), yend=reorder(Words, Values))) +
  geom_text(aes(x=Values, label=Values, hjust=-0.3), color="#389912",family="sans") +
  geom_segment(size=4,colour=visual_data$importance) +
  theme(axis.text=element_text(size=10,family="sans"),axis.title=element_text(size=13,face="bold",family="sans"),strip.text.y = element_text(size=12,family="sans"), plot.title=element_text(size=14,face="bold",family="sans")) +      
  facet_grid(group~., scales = "free")+
  theme_bw()
graphic

可以看到的是"是的"和#34;例如,#34;不共享相同的条形颜色,尽管它们应该根据我的数据规范。

有没有人可以解决这个问题?

1 个答案:

答案 0 :(得分:6)

您需要在aes()中添加颜色并添加scale_colour_identity()

ggplot(visual_data,
       aes(x=0, xend=Values, y=reorder(Words, Values), yend=reorder(Words, Values))) +
  geom_text(aes(x=Values, label=Values, hjust=-0.3), color="#389912",family="sans") +
  geom_segment(size=4, aes(colour=importance)) +
  scale_colour_identity() +
  theme(axis.text=element_text(size=10,family="sans"),
        axis.title=element_text(size=13,face="bold",family="sans"),
        strip.text.y = element_text(size=12,family="sans"), 
        plot.title=element_text(size=14,face="bold",family="sans")) +      
  facet_grid(group~., scales = "free")+
  theme_bw()

enter image description here