runningbirds
runningbirds

Reputation: 6615

ggplot - change shape of legend icon in a theme

Is it possible to make a theme that changes the shape of the legend icon/symbol that is used to identify the different color in a plot?

What I mean is that if you make a line plot:

library(ggplot2)

ggplot(iris, aes(x=Sepal.Length, y = Sepal.Width, color=Species)) +
  geom_line()

You will see 'thin' lines identifying each different group. I don't prefer this.

What I would like is to always make my color identifiers nice solid squares/blocks like this:

ggplot(iris, aes(x=Sepal.Length, y = Sepal.Width, color=Species, fill=Species)) +
  geom_bar(stat='identity')

I'm wondering if there is an option that I can add to a custom ggplot theme to enable this by default? I have some custom made themes for plots and I'd love to be able to add this in, as sometimes its really hard to make out the very faint lines or dots. A solid square is much more noticeable.

Upvotes: 2

Views: 1206

Answers (1)

Z.Lin
Z.Lin

Reputation: 29085

I don't think theme() allows you to override specific aesthetic parameters in the legend key symbols. It deals with the legend key's size, background, etc., while draw_key_XXX covers the key symbols' appearance.

However, if the concern is about re-typing, you can add guides(...) to your customized theme:

theme_customized <- function(...){
  list(guides(color = guide_legend(override.aes = list(size = 10))),

       # optional: the base theme you modify from
       theme_light(), 

       # customized theme options for your theme
       # (I'm using axis.text / panel.grid for illustration)
       theme(axis.text = element_text(size = 15),
             panel.grid.minor.y = element_blank()),

       # any theme options that you may want to set
       # on an ad hoc basis
       theme(...))
}

Using the customized theme:

gridExtra::grid.arrange(

  # with ggplot's default theme_grey
  ggplot(iris, aes(x=Sepal.Length, y = Sepal.Width, color=Species)) +
    geom_line(),

  # customized theme with default options
  ggplot(iris, aes(x=Sepal.Length, y = Sepal.Width, color=Species)) +
    geom_line() +
    theme_customized(),

  # customized theme with additional adhoc specifications
  ggplot(iris, aes(x=Sepal.Length, y = Sepal.Width, color=Species)) +
    geom_line() +
    theme_customized(axis.title = element_text(color = "blue"),
                     panel.background = element_rect(fill = "darkgrey")),
  ncol = 1
)

illustration

Upvotes: 1

Related Questions