How to Modify ggplot2 Barplot Color in R (2 Examples)

On this page you’ll learn how to modify the color of a ggplot2 barchart in the R programming language.

Setting up the Examples

data(iris)                  # Loading example data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa
install.packages("ggplot2") # Install & load ggplot2 package
library("ggplot2")
ggplot(iris,                # Draw basic ggplot2 barchart
       aes(x = Species,
           y = Sepal.Length)) +
  geom_bar(stat = "identity")

r graph figure 1 modify ggplot2 barplot color

Example 1: Create ggplot2 Barchart with Default Color Palette

ggplot(iris,                # Barchart with the default colors of ggplot2
       aes(x = Species,
           y = Sepal.Length,
           fill = Species)) +
  geom_bar(stat = "identity")

r graph figure 2 modify ggplot2 barplot color

Example 2: Create ggplot2 Barchart with User-Defined Color Palette

ggplot(iris,                # Manually defined color palette
       aes(x = Species,
           y = Sepal.Length,
           fill = Species)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("setosa" = "purple",
                               "versicolor" = "yellow",
                               "virginica" = "brown"))

r graph figure 3 modify ggplot2 barplot color

Related Articles

In the following, you may find some further resources on topics such as ggplot2, factors, and plot legends.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top