ggplot2 colors in R-Default colors complete guide

ggplot2 colors in R, Depending on the total number of items in the plot, the ggplot2 program has a set of default colors it uses for the elements.

For instance, the code that follows demonstrates how to make a bar plot with three bars.

library(ggplot2)

Let’s create a data frame

df <- data.frame(team=c('P1', 'P2', 'P3'),
                 points=c(122, 124, 105))

Now we can create a bar plot using the above data frame

Why we need a null hypothesis test? » Why we need a null hypothesis test?. »

ggplot(df, aes(x=team, y=points, fill=team)) +
  geom_bar(stat = "identity")

By default, ggplot2 selects a particular hue for each of the three colors it uses to represent the bars.

To extract the precise hex color codes used in the figure, we may use the hue_pal() function from the scales package.

library(scales)

extract the hex color codes for a three-part layout. for ggplot2

hex <- hue_pal()(3)

Now display hex color codes

hex
"#F8766D" "#00BA38" "#619CFF"

How to interpret the result is as follows:

The red in the scene has the hexadecimal color code #F8766D.

The plot’s green is represented by the hexadecimal color #00BA38.

The blue in the scene has the hexadecimal hue #619CFF.

To overlay the hex color codes on their true colors, we may alternatively use the show_col() function from the scales package:

library(scales)

extract the hex color codes for a three-part layout. for ggplot2

hex <- hue_pal()(3)

hex color codes overlaid on actual colors

show_col(hex)

Additionally, we can make a plot that displays the standard ggplot2 colors for plots with one to eight items by using the code below.

library(scales)

Let’s set the margins of the plot area

par(mai = c(0.1, 0, 0.1, 0), bg = "grey85")

Plot with default ggplot2 colors from 1 to 8

gc.grid <- layout(matrix(1:8, nrow = 8))
for(i in 1:8){
   gc.ramp <- hue_pal()(i)
   plot(c(0, 8), c(0,1),
        type = "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])
   }
}

The hex color codes for each hue in the plot can be shown using the code below.

What is an adaptive clinical trial? »

library(scales)

Now we can display the 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"
[8] "#FF61CC"

You may also like...

Leave a Reply

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

four + fifteen =