2

Is it possible to create a empty ggplot with no data, but draw a legend based on defined values in R?

So the image created is simply the legend?

Originally I thought I could plot the data and print a white rectangle over it, but given that not every background is white, it is unrealistic. I have tried the below, but it looks like ggplot wants some dataframe, therefore I had to add one. Is it possiable not to add one or create blank graph a different way?

library(ggplot2)

Outcome <- c("A", "B", "C", "D",'E')
shots <- rep('Label',5)
xc <-c(1:5)
yc <-c(1:5)
df <-data.frame(shots,Outcome,xc,yc)
p <- ggplot() +
  geom_point(data = df, aes(x = xc, y = yc, fill = Outcome), shape=22, size=4,color = 'black', stroke=1) +

  #Color and Legend
  scale_fill_manual(values=c('chartreuse3','gainsboro','dodgerblue3','firebrick2','cornsilk4'),
                    labels = c("A", "B", "C", "D",'E'), 
                    drop = FALSE) +
  #Theme
  theme(
    panel.background = element_rect(fill = "transparent",colour = NA),
    plot.margin = unit(c(0.1,0.1,0.1,0.1), "cm"),
    plot.title = element_text(size = 14, hjust = 0.5, vjust = 1),
    plot.background = element_rect(fill = "transparent", colour = NA),
    axis.title=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    legend.position = 'left',
    legend.title=element_text(size=15),
    legend.text=element_text(size=15),
    legend.background = element_rect(fill = "transparent")
  )
p

legend

wibeasley
  • 5,000
  • 3
  • 34
  • 62
Jack Armstrong
  • 1,182
  • 4
  • 26
  • 59

1 Answers1

2

Do you want the full plot size, but with the space empty? If so, the override.aes parameter can help. Make the plotted points fully transparent (alpha=0), but the legend points fully opaque (alpha=1).

palette_color <- c("A"='chartreuse3', "B"='gainsboro', "C"='dodgerblue3', "D"='firebrick2', "E"='cornsilk4')

ggplot(df, aes(x = xc, y = yc, fill = Outcome)) +
  geom_point(shape=22, alpha=0) +
  # geom_blank() +
  scale_fill_manual(values=palette_color, drop=FALSE) +
  guides(fill = guide_legend(override.aes = list(alpha=1))) 

legend_only I like your theme modifications, but I left them off here so it's more clear which elements are drawn where.

If this isn't what you're asking for, is it something addressed by geom_blank()?

wibeasley
  • 5,000
  • 3
  • 34
  • 62