Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing colors from a ggtheme theme in ggplot

Tags:

r

colors

ggplot2

I have a pretty nice little plot I've made with ggplot and it looks great. I have some bars and then some crossbars. I'm using the theme_economist() from the ggthemes package and I'd like to make the bars all one color from that theme and the crossbars a contrasting color. But I can't figure out how to reach into the theme and grab out a couple of colors for these elements. I can change them to a named color and I can change them to a specific hex color, but it seems like I should be able to reach into the theme and say, "gimme two contrasting colors from this theme!" How do I do that?

Here's a reprex showing what I have...

library(tidyverse)
library(ggthemes)

prices <- data.frame(year=2001:2010, 
                     price=rnorm(10))
additional_junk <- data.frame(year=2001:2010, 
                              thing=rnorm(10))

g_price <- ggplot() + theme_economist() + 
  scale_fill_economist() + 
  scale_colour_economist() +
  geom_bar(aes(y = price , x = year), 
           data = prices, stat="identity") +
  geom_crossbar(data=additional_junk, aes(x=year, y=thing, 
                                        ymin=0, ymax=0) 
  ) 
g_price

like image 467
JD Long Avatar asked May 25 '18 21:05

JD Long


1 Answers

ggthemes includes a list object ggthemes_data with various palettes and other data used by the package (see below). You could choose from among those colors.

library(ggthemes)

ggthemes_data$economist
$bg
      ebg     edkbg       red    ltgray    dkgray 
"#d5e4eb" "#c3d6df" "#ed111a" "#ebebeb" "#c9c9c9" 

$fg
  blue_gray   blue_dark green_light    blue_mid  blue_light  green_dark        gray  blue_light    red_dark   red_light 
  "#6794a7"   "#014d64"   "#76c0c1"   "#01a2d9"   "#7ad2f6"   "#00887d"   "#adadad"   "#7bd3f6"   "#7c260b"   "#ee8f71" 
green_light       brown 
  "#76c0c1"   "#a18376" 

$stata
$stata$bg
      ebg     edkbg 
"#C6D3DF" "#B2BFCB" 

$stata$fg
  edkblue  emidblue   eltblue   emerald     erose    ebblue  eltgreen     stone      navy    maroon     brown  lavender 
"#3E647D" "#7B92A8" "#82C0E9" "#2D6D66" "#BFA19C" "#008BBC" "#97B6B0" "#D7D29E" "#1A476F" "#90353B" "#9C8847" "#938DD2" 
     teal cranberry     khaki 
"#6E8E84" "#C10534" "#CAC27E"

In addition, as noted by the commenters, you can generate palettes with economist_pal(), for example, economist_pal()(2) or economist_pal(stata=TRUE)(3).

library(scales)

show_col(economist_pal()(9))

enter image description here

show_col(economist_pal(stata=TRUE)(9))

enter image description here

like image 68
eipi10 Avatar answered Sep 25 '22 04:09

eipi10