簡體   English   中英

是否可以將圖例鍵號放置在 ggplot 圖例的元素中?

[英]Is it possible to place legend key numbers inside elements of a ggplot legend?

我正在嘗試 plot map 上的一個區域,以獲取具有很長 label 名稱的數據。 我嘗試了一種解決方法,將 id(行名)連接到標簽的值,以便在 map 上僅顯示短 id,但圖例用作鍵(id:名稱)。 我想知道是否有更優雅的方法來解決這個問題,例如將 id 顯示在 box 元素內,並且只在 box 的右側顯示名稱。 下面是一個最小的可重現示例。

library(sf)
library(ggplot2)
library(gtools)
library(dplyr)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
nc$id <- as.numeric(rownames(nc))

nc <- dplyr::mutate(nc, field_key = paste(id, NAME, sep = ": "))

ggplot2::ggplot(nc) +
  geom_sf(aes(color = field_key)) +
  geom_sf_text(aes(label = id)) +
  scale_color_discrete(breaks = gtools::mixedsort(nc$field_key))

在此處輸入圖像描述

更改以下行會在框內給出一個“a”,但我不清楚為什么,或者是否可以將 a 操作為 id 號。

geom_sf_text(aes(label = id, color = 'white'))

我認為這是您想要的結果:

在此處輸入圖像描述

但恐怕獲得它不是很優雅。 基本上,我只是將圖例文本向左移動,並在前面加上一些空格以保持數字對齊。

library(sf)
library(ggplot2)
library(gtools)
library(dplyr)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
nc$id <- as.numeric(rownames(nc))


nc <- dplyr::mutate(nc, field_key = paste0(c(rep("   ", 9), rep(" ", 90), ""), 
                                           paste(id, NAME, sep = ":     ")),
                    field_key = factor(field_key, levels = field_key))
      
ggplot2::ggplot(nc) +
  geom_sf(aes(color = field_key)) +
  geom_sf_text(aes(label = id)) +
  scale_color_discrete(breaks = gtools::mixedsort(nc$field_key)) +
  theme(legend.text = element_text(margin = margin(0, 0, 0, -24)),
        legend.key.width = unit(20, "points"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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