Closed gnilheb closed 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()
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.
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.
This would save a lot of typing and make the code much easier to read and more reusable.