The ggplot2 package has a list of default colors that it uses for the elements in a plot depending on the number of total elements.
For example, the following code shows how to create a bar plot with three bars:
library(ggplot2) #create data frame df frame(team=c('A', 'B', 'C'), points=c(22, 28, 15)) #create bar plot using df ggplot(df, aes(x=team, y=points, fill=team)) + geom_bar(stat = "identity")
By default, ggplot2 chooses to use a specific shade of red, green, and blue for the bars.
We can use the hue_pal() from the scales package to extract the actual hex color codes used in the plot:
library(scales) #extract hex color codes for a plot with three elements in ggplot2 hex 3) #display hex color codes hex [1] "#F8766D" "#00BA38" "#619CFF"
Here’s how to interpret the output:
- The hex color code for the red in the plot is #F8766D.
- The hex color code for the green in the plot is #00BA38.
- The hex color code for the blue in the plot is #619CFF.
We can use also use show_col() from the scales package to overlay the hex color codes on their actual colors:
library(scales) #extract hex color codes for a plot with three elements in ggplot2 hex 3) #overlay hex color codes on actual colors show_col(hex)
And we can use the following code to create a plot that shows the default ggplot2 colors for plots with one through eight elements:
library(scales) #set margins of plot area par(mai = c(0.1, 0, 0.1, 0), bg = "grey85") #create plot with ggplot2 default colors from 1 to 8 gc.grid 8)) for(i in 1:8){ gc.ramp n", bty="n", xaxt="n", yaxt="n", xlab="", ylab="") for(j in 1:i){ rect(j - 1, 0, j - 0.25, 1, col = gc.ramp[j]) } }
And we can use the following code to display the hex color codes for each color shown in the plot:
library(scales) #display ggplot2 default hex color codes from 1 to 8 for(i in 1:8){ print(hue_pal()(i)) } [1] "#F8766D" [1] "#F8766D" "#00BFC4" [1] "#F8766D" "#00BA38" "#619CFF" [1] "#F8766D" "#7CAE00" "#00BFC4" "#C77CFF" [1] "#F8766D" "#A3A500" "#00BF7D" "#00B0F6" "#E76BF3" [1] "#F8766D" "#B79F00" "#00BA38" "#00BFC4" "#619CFF" "#F564E3" [1] "#F8766D" "#C49A00" "#53B400" "#00C094" "#00B6EB" "#A58AFF" "#FB61D7" [1] "#F8766D" "#CD9600" "#7CAE00" "#00BE67" "#00BFC4" "#00A9FF" "#C77CFF" "#FF61CC"
Additional Resources
The following tutorials explain how to perform other common operations in R:
A Complete Guide to the Best ggplot2 Themes
How to Change Legend Size in ggplot2
How to Remove a Legend in ggplot2