Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use color names specified in data as fill color in geom_bar [duplicate]

Tags:

r

ggplot2

fill

I have a data frame (freqOvertimeHourlyData) like this:

     HOURS INTERVAL BARCOLOR
1     147    16-17  "green"
2     150    17-18  "green"
3     144    18-19  "blue"
4     149    19-20  "red"
5     139    20-21  "red"
6     101    21-22  "red"

Is there a way to create a barplot, using geom_bar, with fill color according to the actual color names explicitly specified as a variable in the data set (column BARCOLOR)? My current plot is made like this:

ggplot(freqOvertimeHourlyData, aes(x = INTERVAL, y = HOURS))+
geom_histogram(stat = "identity")+
theme(legend.position = "none")
like image 807
Johann Horvat Avatar asked Mar 26 '15 06:03

Johann Horvat


2 Answers

If you wish to use the raw values, without scaling, for your aesthetics, then scale_identity can be used. Using "DF" from @Sandy Muspratt's answer:

ggplot(DF, aes(x = INTERVAL, y = HOURS, fill = BARCOLOR))+
  geom_bar(stat = "identity")+
  theme(legend.position = "none") +
  scale_fill_identity()

enter image description here

like image 180
Henrik Avatar answered Nov 13 '22 19:11

Henrik


You need to make sure BARCOLOR is a factor.

You need to tell ggplot to fill the bars with colour - fill = BARCOLOR will do that.

But it doesn't matter to ggplot what the contents of BARCOLOR is, ggplot will use its default colours.

You need to set values, that is, your colours, in scale_fill_manual()

library(ggplot2)

DF = read.table(text = '
     HOURS INTERVAL BARCOLOR
1     147    16-17  "blue"
2     150    17-18  "green"
3     144    18-19  "blue"
4     149    19-20  "red"
5     139    20-21  "black"
6     101    21-22  "green" ', header = TRUE)

str(DF)   # Check BARCOLOR is a factor

ggplot(DF, aes(x = INTERVAL, y = HOURS, fill = BARCOLOR))+
   geom_bar(stat = "identity")+
   theme(legend.position = "none") +
   scale_fill_manual(values = levels(DF$BARCOLOR))

enter image description here

like image 34
Sandy Muspratt Avatar answered Nov 13 '22 19:11

Sandy Muspratt