How to add an arbitrary legend using ggplot2?

Hi,

I'm working on a geom_tile() based visualization and I would like to include a legend that indicates how many users each tile represents. I've mocked up what I would like to see below:

Here is my plot code:

ggplot(funnel_df, 
       aes(x = x, y = y, fill = step_label)) + 
  geom_tile(size = 1, color = "white") + 
  scale_fill_discrete(guide = guide_legend(title = "Steps")) + 
  labs(title = "Checkout Funnel") + 
  theme_minimal() + 
  theme( 
    panel.grid.minor = element_blank(),
    panel.grid.major = element_blank(), 
    axis.text = element_blank(),
    axis.title = element_blank()
    )

I attempted to add aes(size =1) thinking that I could then use scale_size_manual to set a manual label to the legend guide. That, however, causes the tiles to disappear:

ggplot(funnel_df, 
       aes(x = x, y = y, fill = step_label)) + 
  geom_tile(**aes(size = 1)**, color = "white") + 
  scale_fill_discrete(guide = guide_legend(title = "Steps")) + 
  labs(title = "Checkout Funnel") + 
  theme_minimal() + 
  theme( 
    panel.grid.minor = element_blank(),
    panel.grid.major = element_blank(), 
    axis.text = element_blank(),
    axis.title = element_blank()
    )

I can provide more complete code if needed, but am hoping for suggestions for either:
a) how to add an arbitrary legend or
b) why does setting aes(size = 1) make the tiles disappear?

For an arbitrary legend item consider this code; it is built on color scale based on a factor variable.

In my case I am:

  1. adding a new level to the Iris dataset (Iris germanica - the type species of Iris genus) via forcats::fct_expand()
  2. plotting the chart with drop = FALSE argument to the color scale call of my ggplot
library(tidyverse)

chart_src <- iris %>% 
  mutate(Species = fct_expand(Species, "germanica"))


ggplot(chart_src, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point() +
  scale_color_discrete(drop = FALSE)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.