[英]Legend as filled rectangles in plot area
我正在為客戶編寫圖表,並且樣式要求圖例(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紅色的事實無關緊要:顏色是手動設置的。另外,顯然我需要其他填充變量的標簽)
這已足夠,但我想知道:
annotate
更自動的解決方案嗎? 簡短的回答是否定的,沒有辦法“自動檢測到將圖例放在圖中的正確位置”,至少不會有一個總是有效的。 在某些時候,你將不得不自己擺弄它。
您可以通過以下方式將默認圖例移動到繪圖中:
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")
如果這對你有吸引力的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.