One-line Code using viridis for How to change the color scale in ggplot plots

This is a small code snippet to explain how to change the color scale of a ggplot.

Continuous Scale

Package: viridis Function: scale_fill_viridis_c() (since it’s a continuous scaled value)

library(dplyr)
library(ggplot2)
library(viridis)
mtcars %>% tibble::rownames_to_column('Car') %>%
  tidyr::separate('Car',c('Brand','Model'), remove = F) %>%
  group_by(Brand) %>%
  summarize(avg_mpg = mean(mpg)) %>%
  ggplot() + geom_bar(aes(reorder(Brand,avg_mpg),avg_mpg, fill = avg_mpg), stat = 'identity') + 
  scale_fill_viridis_c() +
  theme_minimal() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(
    title = 'How to arrange Ggplot Bar plot',
    x = 'mpg') 

Discrete Scale

Package: viridis Function: scale_fill_viridis_d() (since it’s a discrete scaled value)

library(dplyr)
library(ggplot2)
library(viridis)
mtcars %>% tibble::rownames_to_column('Car') %>%
  tidyr::separate('Car',c('Brand','Model'), remove = F) %>%
  group_by(Brand) %>%
  summarize(avg_mpg = mean(mpg)) %>%
  ggplot() + geom_bar(aes(reorder(Brand,avg_mpg),avg_mpg, fill = Brand), stat = 'identity') + 
  scale_fill_viridis_d() +
  theme_minimal() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(
    title = 'How to arrange Ggplot Bar plot',
    x = 'mpg') 

How to change viridis theme in ggplot

Package: viridis Function: scale_fill_viridis_c() (since it’s a continuous scaled value) with the option parameter

Parameter

Option: “magma” (or “A”), “inferno” (or “B”), “plasma” (or “C”), “viridis” (or “D”, the default option) and “cividis” (or “E”)

library(dplyr)
library(ggplot2)
library(viridis)
mtcars %>% tibble::rownames_to_column('Car') %>%
  tidyr::separate('Car',c('Brand','Model'), remove = F) %>%
  group_by(Brand) %>%
  summarize(avg_mpg = mean(mpg)) %>%
  ggplot() + geom_bar(aes(reorder(Brand,avg_mpg),avg_mpg, fill = avg_mpg), stat = 'identity') + 
  scale_fill_viridis_c(option = 'magma') +
  theme_minimal() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(
    title = 'How to arrange Ggplot Bar plot',
    x = 'mpg') 

How to reverse/inverse the color scale of a viridis theme in ggplot

Package: viridis Function: scale_fill_viridis_c() (since it’s a continuous scaled value) with the option parameter

Paramater Direction: -1 (Default is +1)

library(dplyr)
library(ggplot2)
library(viridis)
mtcars %>% tibble::rownames_to_column('Car') %>%
  tidyr::separate('Car',c('Brand','Model'), remove = F) %>%
  group_by(Brand) %>%
  summarize(avg_mpg = mean(mpg)) %>%
  ggplot() + geom_bar(aes(reorder(Brand,avg_mpg),avg_mpg, fill = avg_mpg), stat = 'identity') + 
  scale_fill_viridis_c(option = 'magma', direction = -1) +
  theme_minimal() + 
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) + labs(
    title = 'How to arrange Ggplot Bar plot',
    x = 'mpg') 

 
comments powered by Disqus