簡體   English   中英

圖例中的填充矩形圖例

[英]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紅色的事實無關緊要:顏色是手動設置的。另外,顯然我需要其他填充變量的標簽)

這已足夠,但我想知道:

  1. 有沒有辦法檢測ggplot在哪里有空白區域並將圖例放在那里(或創建用於放置圖例的空白區域)?
  2. 通常是一個比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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM