Search code examples
rggplot2histogram

ggplot histogram colour by group not working


Ok I have a df like this

a <- c(1,2,2,3)
b <- c(4,5,6,7)
ab <- data.frame(a, b)
ab 

I plot a simple histogram with ggplot and try colour by x variable.

ggplot(ab, aes(x=a, fill=a)) +geom_histogram()

The output plot does not colour. Im clearly making a small error somewhere.

Output graph looks like this


Solution

  • Another way of doing it, a need to be factor

        library(ggplot2)
        a <- c(1,2,2,3)
        b <- c(4,5,6,7)
        ab <- data.frame(a, b)
        ab 
        
        ggplot(ab, aes(x=a, fill=as.factor(a))) +
      geom_histogram()
    

    enter image description here