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:
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.