ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (2024)

  • Home
  • Explorer
    • Prepare the data
    • Simple plots
    • Use a single color
    • Change colors by groups
      • Default colors
      • Change colors manually
      • Use RColorBrewer palettes
      • Use Wes Anderson color palettes
    • Use gray colors
    • Continuous colors
      • Gradient colors for scatter plots
      • Gradient colors for histogram plots
      • Gradient between n colors
    • Infos

    The goal of this article is to describe how to change the color of a graph generated using R software and ggplot2 package. A color can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”). The different color systems available in R are described at this link : colors in R.

    In this R tutorial, you will learn how to :

    • change colors by groups (automatically and manually)
    • use RColorBrewer and Wes Anderson color palettes
    • use gradient colors

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (1)


    ToothGrowth and mtcars data sets are used in the examples below.

    # Convert dose and cyl columns from numeric to factor variablesToothGrowth$dose <- as.factor(ToothGrowth$dose)mtcars$cyl <- as.factor(mtcars$cyl)head(ToothGrowth)
    ## len supp dose## 1 4.2 VC 0.5## 2 11.5 VC 0.5## 3 7.3 VC 0.5## 4 5.8 VC 0.5## 5 6.4 VC 0.5## 6 10.0 VC 0.5
    head(mtcars)
    ## mpg cyl disp hp drat wt qsec vs am gear carb## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

    Make sure that the columns dose and cyl are converted as factor variables using the R script above.

    library(ggplot2)# Box plotggplot(ToothGrowth, aes(x=dose, y=len)) +geom_boxplot()# scatter plotggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (3)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (4)

    # box plotggplot(ToothGrowth, aes(x=dose, y=len)) + geom_boxplot(fill='#A4A4A4', color="darkred")# scatter plotggplot(mtcars, aes(x=wt, y=mpg)) + geom_point(color='darkblue')

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (5)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (6)

    Default colors

    The following R code changes the color of the graph by the levels of dose :

    # Box plotbp<-ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + geom_boxplot()bp# Scatter plotsp<-ggplot(mtcars, aes(x=wt, y=mpg, color=cyl)) + geom_point()sp

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (7)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (8)

    The lightness (l) and the chroma (c, intensity of color) of the default (hue) colors can be modified using the functions scale_hue as follow :

    # Box plotbp + scale_fill_hue(l=40, c=35)# Scatter plotsp + scale_color_hue(l=40, c=35)

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (9)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (10)

    Note that, the default values for l and c are : l = 65, c = 100.

    Change colors manually

    A custom color palettes can be specified using the functions :

    • scale_fill_manual() for box plot, bar plot, violin plot, etc
    • scale_color_manual() for lines and points
    # Box plotbp + scale_fill_manual(values=c("#999999", "#E69F00", "#56B4E9"))# Scatter plotsp + scale_color_manual(values=c("#999999", "#E69F00", "#56B4E9"))

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (11)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (12)

    Note that, the argument breaks can be used to control the appearance of the legend. This holds true also for the other scale_xx() functions.

    # Box plotbp + scale_fill_manual(breaks = c("2", "1", "0.5"), values=c("red", "blue", "green"))# Scatter plotsp + scale_color_manual(breaks = c("8", "6", "4"), values=c("red", "blue", "green"))

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (13)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (14)

    The built-in color names and a color code chart are described here : color in R.

    Use RColorBrewer palettes

    The color palettes available in the RColorBrewer package are described here : color in R.

    # Box plotbp + scale_fill_brewer(palette="Dark2")# Scatter plotsp + scale_color_brewer(palette="Dark2")

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (15)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (16)

    The available color palettes in the RColorBrewer package are :

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (17)

    Use Wes Anderson color palettes

    Install and load the color palettes as follow :

    # Installinstall.packages("wesanderson")# Loadlibrary(wesanderson)

    The available color palettes are :

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (18)

    library(wesanderson)# Box plotbp+scale_fill_manual(values=wes_palette(n=3, name="GrandBudapest"))# Scatter plotsp+scale_color_manual(values=wes_palette(n=3, name="GrandBudapest"))

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (19)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (20)

    The functions to use are :

    • scale_colour_grey() for points, lines, etc
    • scale_fill_grey() for box plot, bar plot, violin plot, etc
    # Box plotbp + scale_fill_grey() + theme_classic()# Scatter plotsp + scale_color_grey() + theme_classic()

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (21)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (22)

    Change the gray value at the low and the high ends of the palette :

    # Box plotbp + scale_fill_grey(start=0.8, end=0.2) + theme_classic()# Scatter plotsp + scale_color_grey(start=0.8, end=0.2) + theme_classic()

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (23)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (24)

    Note that, the default value for the arguments start and end are : start = 0.2, end = 0.8

    The graph can be colored according to the values of a continuous variable using the functions :

    • scale_color_gradient(), scale_fill_gradient() for sequential gradients between two colors
    • scale_color_gradient2(), scale_fill_gradient2() for diverging gradients
    • scale_color_gradientn(), scale_fill_gradientn() for gradient between n colors

    Gradient colors for scatter plots

    The graphs are colored using the qsec continuous variable :

    # Color by qsec valuessp2<-ggplot(mtcars, aes(x=wt, y=mpg, color=qsec)) + geom_point()sp2# Change the low and high colors# Sequential color schemesp2+scale_color_gradient(low="blue", high="red")# Diverging color schememid<-mean(mtcars$qsec)sp2+scale_color_gradient2(midpoint=mid, low="blue", mid="white", high="red", space ="Lab" )

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (25)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (26)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (27)

    Gradient colors for histogram plots

    set.seed(1234)x <- rnorm(200)# Histogramhp<-qplot(x =x, fill=..count.., geom="histogram") hp# Sequential color schemehp+scale_fill_gradient(low="blue", high="red")

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (28)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (29)

    Note that, the functions scale_color_continuous() and scale_fill_continuous() can be used also to set gradient colors.

    Gradient between n colors

    # Scatter plot# Color points by the mpg variablesp3<-ggplot(mtcars, aes(x=wt, y=mpg, color=mpg)) + geom_point()sp3# Gradient between n colorssp3+scale_color_gradientn(colours = rainbow(5))

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (30)ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (31)

    This analysis has been performed using R software (ver. 3.1.2) and ggplot2 (ver. 1.0.0)


    Enjoyed this article? I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter, Facebook or Linked In.

    Show me some love with the like buttons below... Thank you and please don't forget to share and comment below!!

    Avez vous aimé cet article? Je vous serais très reconnaissant si vous aidiez à sa diffusion en l'envoyant par courriel à un ami ou en le partageant sur Twitter, Facebook ou Linked In.

    Montrez-moi un peu d'amour avec les like ci-dessous ... Merci et n'oubliez pas, s'il vous plaît, de partager et de commenter ci-dessous!



    Recommended for You!


    Machine Learning Essentials: Practical Guide in R
    Practical Guide to Cluster Analysis in R
    Practical Guide to Principal Component Methods in R
    R Graphics Essentials for Great Data Visualization
    Network Analysis and Visualization in R
    More books on R and data science

    Recommended for you

    This section contains best data science and self-development resources to help you on your path.

    Coursera - Online Courses and Specialization

    Data science

    Popular Courses Launched in 2020

    Trending Courses

    Books - Data Science

    Our Books

    Others



    Want to Learn More on R Programming and Data Science?

    Follow us by Email

    On Social Networks:

    Get involved :
    Click to follow us on Facebook and Google+ :
    Comment this article by clicking on "Discussion" button (top-right position of this page)

    ggplot2 colors : How to change colors automatically and manually? - Easy Guides - Wiki (2024)
    Top Articles
    Boa Constrictor Morphs: Exploring Their Diversity | KCN
    Normal - Boa Constrictor Traits
    Instructional Resources
    Phone Number For Walmart Automotive Department
    Cad Calls Meriden Ct
    Culver's Flavor Of The Day Wilson Nc
    50 Meowbahh Fun Facts: Net Worth, Age, Birthday, Face Reveal, YouTube Earnings, Girlfriend, Doxxed, Discord, Fanart, TikTok, Instagram, Etc
    Devourer Of Gods Resprite
    World Cup Soccer Wiki
    4302024447
    Notisabelrenu
    Nwi Arrests Lake County
    Maplestar Kemono
    Second Chance Maryland Lottery
    Po Box 35691 Canton Oh
    Soccer Zone Discount Code
    Diamond Piers Menards
    Candy Land Santa Ana
    Lola Bunny R34 Gif
    Hdmovie2 Sbs
    Is A Daytona Faster Than A Scat Pack
    Melissababy
    Mc Donald's Bruck - Fast-Food-Restaurant
    Miltank Gamepress
    ‘The Boogeyman’ Review: A Minor But Effectively Nerve-Jangling Stephen King Adaptation
    Www.patientnotebook/Atic
    Craigslist Apartments Baltimore
    MyCase Pricing | Start Your 10-Day Free Trial Today
    The Creator Showtimes Near R/C Gateway Theater 8
    Craigslist Apartments In Philly
    Foodsmart Jonesboro Ar Weekly Ad
    Why comparing against exchange rates from Google is wrong
    Kempsville Recreation Center Pool Schedule
    Grove City Craigslist Pets
    Brenda Song Wikifeet
    ShadowCat - Forestry Mulching, Land Clearing, Bush Hog, Brush, Bobcat - farm & garden services - craigslist
    Tra.mypatients Folio
    Haley Gifts :: Stardew Valley
    Agematch Com Member Login
    Omnistorm Necro Diablo 4
    42 Manufacturing jobs in Grayling
    ATM Near Me | Find The Nearest ATM Location | ATM Locator NL
    Property Skipper Bermuda
    Tirage Rapid Georgia
    Woodman's Carpentersville Gas Price
    Uc Santa Cruz Events
    301 Priest Dr, KILLEEN, TX 76541 - HAR.com
    Casamba Mobile Login
    If You're Getting Your Nails Done, You Absolutely Need to Tip—Here's How Much
    Florida Lottery Powerball Double Play
    Free Carnival-themed Google Slides & PowerPoint templates
    Affidea ExpressCare - Affidea Ireland
    Latest Posts
    Article information

    Author: Edwin Metz

    Last Updated:

    Views: 5661

    Rating: 4.8 / 5 (58 voted)

    Reviews: 89% of readers found this page helpful

    Author information

    Name: Edwin Metz

    Birthday: 1997-04-16

    Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

    Phone: +639107620957

    Job: Corporate Banking Technician

    Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

    Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.