r - 为ggplot2中的每个图例分配不同的背景颜色

标签 r ggplot2 legend background-color

page显示了如何使用ggplot函数操作guide_legend的多个图例,例如顺序,标题颜色。我想知道是否可以分别修改每个图例的背景颜色。谢谢!

ggplot(mpg, aes(displ, cty)) +
  # I tired to use legend.background and a list of colors in fill to individually change the color, but is it not working
  theme(legend.background=element_rect(fill=c('brown','grey','whie'))) +
  geom_point(aes(size = hwy, colour = cyl, shape = drv)) +
  guides(
    colour = guide_colourbar(order = 1),
    # title.theme allows individual adjustment of title color, I wonder if similar can be done for legend background color
    shape = guide_legend(order = 2,title.theme = element_text(color='green')),
    size = guide_legend(order = 3,label.theme=element_text(color='red'))
  )

最佳答案

我认为没有办法将多种颜色发送到legend.background。如果这对您确实很重要,那么您可能需要在最后的情节中破解这些怪胎。这是一个无需使用任何外部程序包即可完成的小功能:

recolor_legends <- function(gg_plot, col)
{
  p2      <- ggplotGrob(gg_plot)
  grobs   <- p2$grobs[which(p2$layout$name == "guide-box")][[1]]$grobs
  legends <- grobs[sapply(grobs, function(x) any(grepl("grobs", names(x))))]
  bgs     <- lapply(legends, function(x) {
    x$grobs[x$layout$name == "background"][[1]]
  })
  bgs <- mapply(function(x, y) {x$gp$fill <- y; x}, bgs, col, SIMPLIFY = FALSE)
  legends <- mapply(function(x, y){
    x$grobs[x$layout$name == "background"][[1]] <- y; x
  }, legends, bgs, SIMPLIFY = FALSE)
  grobs[sapply(grobs, function(x) any(grepl("grobs", names(x))))] <- legends
  p2$grobs[which(p2$layout$name == "guide-box")][[1]]$grobs <- grobs
  plot(p2)
}
因此,假设我有以下情节:
p <- ggplot(mpg, aes(displ, cty)) +
  geom_point(aes(size = hwy, colour = cyl, shape = drv)) +
  guides(
    colour = guide_colourbar(order = 1),
    shape = guide_legend(order = 2,
    title.theme = element_text(color = 'green')),
    size = guide_legend(order = 3, label.theme = element_text(color = 'red'))
  )

p
enter image description here
我可以做
recolor_legends(p, c("red", "blue", "green"))
enter image description here

关于r - 为ggplot2中的每个图例分配不同的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63576583/

相关文章:

仅当有两个或多个空格时才替换字符串中的空格

R Shiny - 调整数字输入框的大小

r - 使用 treemapify 在 R 中绘制 TreeMap

r - 根据未在 x、y、颜色映射/plot_ly 条件文本中使用的辅助子分组,有条件地为热图单元格分配颜色和标签

r - 在R中使用SVM实现多类分类

R:如何检查向量元素是否相同

r - 如何在ggplot中突出显示沿曲线的点

d3.js - NVD3 : How to get values from tooltip or legend instead of labels?

plot - 在图例和标签中使用 LaTeX?

R按因子绘制颜色图例