简体   繁体   中英

Legend as filled rectangles in plot area

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:

  1. 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)?
  2. Is there in general a more automatic solution than annotate ?

The short answer is no, there is no way to "automatically detect the correct place to put the legend within the plot", at least not one that will always work. At some point you will have to fiddle with it yourself.

You can move the default legend into the plot via something like:

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() + 
    theme(legend.position = c(0.25,0.8),
                legend.direction = "horizontal")

if that's appealing to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM