Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associate a color palette with ggplot2 theme

Tags:

r

ggplot2

I want my ggplot2 theme to use a specific set of colors, but don't see how to avoid a separate line outside of the theme.

I have this data:

library(ggplot2)
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)

And here's a dummy theme I plot with:

mytheme <- theme(panel.grid.major = element_line(size = 2))

ggplot(mycars, aes(x = wt, y = mpg)) +
  geom_point(aes(color = cyl)) +
  mytheme

without custom colors

I want the point colors to default to my custom palette:

mycolors <- c("deeppink", "chartreuse", "midnightblue")

Can I somehow add that to my ggplot2 theme so that I don't constantly repeat this extra line of code at the end:

ggplot(mycars, aes(x = wt, y = mpg)) +
  geom_point(aes(color = cyl)) +
  mytheme +
  scale_color_manual(values = mycolors)

with colors

I tried:

mytheme2 <- mytheme + scale_color_manual(values = mycolors)

But got:

Error: Don't know how to add scale_color_manual(values = mycolors) to a theme object

like image 375
Sam Firke Avatar asked Apr 07 '16 12:04

Sam Firke


People also ask

Which package can you use for extra themes and color scale for ggplot2?

The ggthemr package was developed by a friend of mine, Ciarán Tobin, who works with me at KillBiller and Edgetier. The package gives a quick and easy way to completely change the look and feel of your ggplot2 figures, as well as quickly create a theme based on your own, or your company's, colour palette.

What colors does Ggplot recognize?

By default, ggplot2 chooses to use a specific shade of red, green, and blue for the bars.

What are the themes in ggplot2?

Change the default ggplot theme by using the list of the standard themes available in ggplot2 R package. Our selection of best ggplot themes for professional publications or presentations, include: theme_classic(), theme_minimal() and theme_bw(). Another famous theme is the dark theme: theme_dark().

How do you set a specific color in R?

In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.


1 Answers

Hi you can put your custom element in a list :

# Data
library("ggplot2")
mycars <- mtcars
mycars$cyl <- as.factor(mycars$cyl)

# Custom theme
mytheme <- theme(panel.grid.major = element_line(size = 2))
mycolors <- c("deeppink", "chartreuse", "midnightblue")
# put the elements in a list
mytheme2 <- list(mytheme, scale_color_manual(values = mycolors))

# plot 
ggplot(mycars, aes(x = wt, y = mpg)) +
  geom_point(aes(color = cyl)) +
  mytheme2
like image 114
Victorp Avatar answered Oct 02 '22 16:10

Victorp