I'm using ggplot2 in R to create some bar charts, but I'm struggling with the color settings. I want to change both the solid color inside the bars and the color of the borders. Additionally, I’m trying to figure out how to assign specific colors to different categories rather than using the default palette. Is there a difference between using the color and fill arguments, and where should these be placed (inside or outside aes()) to ensure the legend updates correctly?
3 answers
In ggplot2, the two primary arguments for bar colors are fill (the interior color) and color (the outline color).
-
Fixed Color: If you want all bars to be the same color, place the argument outside the
aes()function. For example:geom_bar(fill = "steelblue", color = "black"). -
Color by Variable: If you want colors to represent data categories, place it inside
aes():geom_bar(aes(fill = category_variable)).
To use your own specific colors, add the scale_fill_manual() layer to your plot. You can provide a vector of hex codes or color names: + scale_fill_manual(values = c("Group1" = "#FF5733", "Group2" = "#33FF57")).
Adding to Elena's point, if you are working with large datasets and don't want to pick every color manually, you should look into scale_fill_brewer() for pre-defined professional palettes or scale_fill_viridis_d() for color-blind friendly options. It saves a lot of time and ensures your charts remain accessible.
Don't forget that if you use geom_col() instead of geom_bar(), the color logic remains exactly the same. The only difference is that geom_col() expects you to provide a y variable for the bar heights, whereas geom_bar() counts the occurrences for you.
I agree with Sarah. Many people get confused between the two, but since geom_bar is just a specialized case of geom_col (with a statistical transformation), mastering the color and fill aesthetics in one will instantly make you proficient in the other as well.
Marcus is spot on. I used scale_fill_brewer(palette = "Set3") for my last presentation and it made the categorical differences much clearer than the default "salmon and teal" look.