I'm writing charts for a client and the style requires the legend to be (a) placed within the plotting area and (b) mapping fill to filled rectangles with labels. My current attempt looks like this:
library(ggplot2)
library(dplyr)
data(diamonds)
diamonds %>%
group_by(color, cut) %>%
summarise(price = mean(price)) %>%
#
ggplot(aes(x = color, y = price, fill = cut)) +
geom_bar(stat = "identity",
position = "dodge") +
theme_bw() +
annotate("rect", xmin = "D", xmax = "E", ymin = 6000, ymax = 6500, fill = "red") +
annotate("text", x = 1.5, y = 6250, label = "Fair")

(The fact that the colour is "red" and not the ggplot red is irrelevant: the colours are manually set. Also, obviously I would need the labels for the other fill variables)
This is adequate, but I would like to know:
- Is there a way to detect where ggplot has white space and place the legend there (or create white space in which to place the legend)?
- Is there in general a more automatic solution than
annotate?