我正在为客户编写图表,并且样式要求图例(a)放置在绘图区域内,(b)将填充映射到带有标签的填充矩形 . 我目前的尝试看起来像这样:
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")
(颜色为“红色”而非ggplot红色的事实无关紧要:颜色是手动设置的 . 另外,显然我需要其他填充变量的标签)
这已足够,但我想知道:
-
有没有办法检测ggplot在哪里有空白区域并将图例放在那里(或创建用于放置图例的空白区域)?
-
通常是否比
annotate
更自动的解决方案?
1 回答
简短的回答是否定的,没有办法"automatically detect the correct place to put the legend within the plot",至少没有办法永远有效 . 在某些时候,你将不得不自己摆弄它 .
您可以通过以下方式将默认图例移动到图中:
如果这对你有吸引力的话 .