wilkelab / cowplot

cowplot: Streamlined Plot Theme and Plot Annotations for ggplot2
https://wilkelab.org/cowplot/
704 stars 84 forks source link

Add key_glyph definition to theme #150

Closed gnilheb closed 4 years ago

gnilheb commented 4 years ago

I look at and make lots of time series plots for work. I was happy recently to learn about the rectangle_key_glyph function as it eliminated the need for an ex post facto illustrator clean up on the non-publication ready default ggplot legend. The following code use produces the desired result.

  geom_point(key_glyph=rectangle_key_glyph( # create nice looking squares in legend
               fill=color,
               color='black',
               linetype=1,
               size=1.0,
               padding=margin(0, 0, 0, 0))

My only request is to either show how to put this in a custom theme or rework it so that it can be put into a theme so that I don't have to repeat it for every geom_point(). Since I already use custom themes extensively. My imagined idea would look something like this.

reusable_legend_theme <- function() {
  theme( 
    legend.text = element_text(color="black", size=18, face="bold"),
    legend.title = element_text(color="black", size=18, face="bold"),
    legend.background = element_rect(fill="#EDEDED",
                                     size=1, linetype="solid", 
                                     colour ="black"),
   legend.position = c(0.89, 0.88),
   key_glyph=rectangle_key_glyph( # create nice looking squares in legend
               fill=color,
               color='black',
               linetype=1,
               size=1.0,
               padding=margin(0, 0, 0, 0)
  )
}

ggplot(data, aes(x = DateTime, y=Value, color = Variable)) +
geom_point()+
reusable_legend_theme()

This would save a lot of typing and make the code much easier to read and more reusable.

clauswilke commented 4 years ago

What you're requesting is not something the current ggplot2 theme mechanism supports. Also, key glyphs have to be geom specific. For example, your glyph wouldn't work with geoms that use fill rather than colour. However, there are two ways you can simplify your code. First, define a function draw_key_*, where * is some name for your key glyph. E.g., draw_key_myrect(). Then, you can set the key glyph by that name:

library(ggplot2)
library(cowplot)

draw_key_myrect <- rectangle_key_glyph( # create nice looking squares in legend
  fill=color,
  color='black',
  linetype=1,
  size=1.0,
  padding=margin(0, 0, 0, 0)
)

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point(key_glyph="myrect")

Second, you can define new geoms that automatically set the key glyph:


geom_point2 <- function(...) geom_point(..., key_glyph="myrect")

ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
  geom_point2()