Specify Different Group Colors in ggplot2 Graphics in R (2 Examples)
In this tutorial, I’ll illustrate how to specify different group colors in a ggplot2 graph in the R programming language.
Setting up the Examples
data(iris) # Loading example data frame 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 |
data(iris) # Loading example data frame 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") |
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2")
ggplot(iris, # ggplot2 graph without colors aes(x = Sepal.Length, group = Species)) + geom_boxplot() |
ggplot(iris, # ggplot2 graph without colors aes(x = Sepal.Length, group = Species)) + geom_boxplot()
Example 1: Changing Colors of ggplot2 Plot by Group
ggplot(iris, # Adjusting color aes(x = Sepal.Length, color = Species)) + geom_boxplot() |
ggplot(iris, # Adjusting color aes(x = Sepal.Length, color = Species)) + geom_boxplot()
Example 2: Changing Fill Colors of ggplot2 Plot by Group
ggplot(iris, # Adjusting fill aes(x = Sepal.Length, fill = Species)) + geom_boxplot() |
ggplot(iris, # Adjusting fill aes(x = Sepal.Length, fill = Species)) + geom_boxplot()
Related Articles & Further Resources
Please find some additional R programming tutorials on topics such as ggplot2, lines, graphics in R, and colors in the following list: