5

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")
Henrik
  • 65,555
  • 14
  • 143
  • 159
Johann Horvat
  • 1,285
  • 1
  • 14
  • 18

2 Answers2

10

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

Henrik
  • 65,555
  • 14
  • 143
  • 159
3

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

Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122