繁体   English   中英

用 R ggplot2 为图例键标签着色并移除键

[英]Color legend key labels with R ggplot2 and remove the keys

如何用 R ggplot2为图例键标签着色并隐藏键本身?

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + 
geom_point()

在某种程度上,图例仅包含文本标签468分别以红色、绿色和蓝色着色。

没有办法直接使用theme来做到这一点,因为element_text不会接受矢量化输入。 通过关闭剪辑并在图例应该是的位置绘制一些文本,可能最容易伪造它:

library(ggplot2)

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + 
geom_point() +
  geom_text(data = data.frame(wt = c(6, 6, 6, 6), mpg = c(20, 22.5, 25, 27.5),
                              cyl = c(levels(factor(mtcars$cyl)), "cyl"),
                              colour = c(levels(factor(mtcars$cyl)), "cyl")),
            aes(label = colour)) +
  coord_cartesian(xlim = c(1.5, 5.5), clip = "off") +
  scale_color_manual(values = c("blue", "green", "red", "black")) +
  theme(legend.position = "none",
        plot.margin = margin(10, 50, 10, 10))

在此处输入图像描述

艾伦的回答也很好,但这是一种更自动化的方法,方法是制作自己的自定义指南 function。

library(ggplot2)

guide_textcolourguide <- function(...) {
  guide <- guide_legend(...)
  class(guide) <- c("guide", "textcolourguide", "legend")
  guide
}

guide_gengrob.textcolourguide <- function(guide, theme) {
  legend <- NextMethod()

  # Figure out what are keys and labels
  keys <- grep("^key(?!.*bg)", legend$layout$name, perl = TRUE)
  labels <- grep("^label", legend$layout$name)
  
  # Recolour the labels based on keys, assumes parallel ordering
  newlabels <- mapply(function(key, lab) {
    colour <- legend$grobs[[key]]$gp$col
    lab <- legend$grobs[[lab]]
    lab$children[[1]]$children[[1]]$gp$col <- colour
    return(lab)
  }, key = keys, lab = labels, SIMPLIFY = FALSE)
  
  # Replace labels
  legend$grobs[labels] <- newlabels
  
  # Purge keys
  gtable::gtable_filter(legend, "key", invert = TRUE)
}


ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) + 
  geom_point() +
  scale_colour_discrete(guide = "textcolourguide")

代表 package (v0.3.0) 于 2020 年 8 月 13 日创建

您还可以通过重命名cyl变量并使用element_markdown作为图例来使用ggtext 可能有更优雅的方法来确保因子水平匹配......但这是一种以编程方式将 colors 提供给图例的方法。

library(ggplot2)
library(dplyr)
library(ggtext)

setColors <- function(x, col="red") 
    paste0("<span style = 'color:", col, ";'>", x, "</span>")

mycols <- setNames(colorspace::rainbow_hcl(length(unique(mtcars$cyl))), 
                   unique(sort(mtcars$cyl)))

mtcars %>% 
    mutate(cyl = factor(setColors(cyl, col= mycols[as.character(cyl)]), 
                        unique(setColors(cyl, col = mycols[as.character(cyl)]))[
                            order(unique(cyl))])) %>% 
    ggplot(aes(wt, mpg, colour = cyl)) + 
    geom_point() +
    theme(legend.text = element_markdown()) +
    scale_color_manual(values = unname(mycols))

代表 package (v0.3.0) 于 2020 年 8 月 13 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM