Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colours in ggplot (geom_segment)

Tags:

r

ggplot2

how can color geom_segments according to a factor in the data when facet_grid is used? My approach fails, as the assignment of colors is wrong.

Here's some data:

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

This code creates a plot:

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

What can be seen is that "yeah" and "what", for instance, do not share the same bar color, although they should according to my data specification.

Has anyone a solution to this?

like image 689
MaHo Avatar asked Dec 25 '22 08:12

MaHo


1 Answers

You need to put colour in aes() and add 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

like image 183
erc Avatar answered Dec 28 '22 08:12

erc