14
votes

I am generating some basic barplots in ggplot2 using geom_bar. I would like the number to be listed in the same color above each bar and I am using geom_text. I am filling the bars by using scale_fill_manual(values = alpha(c("#000000", "#FF5733"))). The problem that I am having is that the text above the bars is not changing to the custom coloring. The default R colors are remaining.

library(ggplot2)
Area <- c("Option1", "Option2", "Option3")
Count <- c(193, 56, 4,240, 10, 25)
Type <- c("car", "car", "car", "bike", "bike", "bike")
p <- data.frame(Area, Count, Type)

ggplot(p, aes(x=Area, y=Count, color=Type)) + 
        geom_bar(stat="identity", position="dodge", aes(fill=Type), color="black")  +
        scale_fill_manual(values = alpha(c("#000000", "#FF5733"))) +
        geom_text(aes(label=Count), position=position_dodge(width = 0.9), vjust=-0.40)

I have tried the following to no avail:

  1. At one point I decided that if I could just have the text black, I would accept it and move on, but when I did this, the positioning failed and centered both texts for a single "Option" instead of keeping the text over their respective bar.

    geom_text(aes(label=Count), color="black", position=position_dodge(width = 0.9), vjust=-0.40)

  2. Then I tried this:

    geom_text(aes(label=Count, color=c("#000000", "#FF5733")), position=position_dodge(width = 0.9), vjust=-0.40)

I get the following error with this adjustment: Error: Aesthetics must be either length 1 or the same as the data (6): label, colour, x, y

I think this is because there are 6 bars but only 2 colors specified. However, when I add the colors in 4 more times, it just gets further from what I want.

I tried to post images, but I don't have enough points yet! Sorry!

Thanks for any and all help provided. I am running RStudio:

R version 3.2.3 (2015-12-10)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.6 (El Capitan)
[1] ggplot2_2.1.0

Peace.

1

1 Answers

24
votes

Try adding the colour option to the geom_text aesthetic mappings and assign your custom colours to the two factor levels of Type with scale_colour_manual

ggplot(p, aes(x=Area, y=Count, color=Type)) + 
        geom_bar(stat="identity", position="dodge", aes(fill=Type), color="black")  +
    scale_fill_manual(values = alpha(c("#000000", "#FF5733"))) +
    geom_text(aes(label=Count, colour=Type), 
             position=position_dodge(width = 0.9), 
             vjust=-0.40) +
    scale_colour_manual(values=c("#000000", "#FF5733"))