如何在ggplot2中模拟将审美传递给面板背景?

问题描述 投票:3回答:2

我在这个堆栈溢出问题中读到了一个聪明的方法来模拟使用geom_rect设置美学到面板背景。

Conditionally change panel background with facet_grid?

不幸的是,如果你想在绘图中添加其他颜色,它就不起作用。颜色混合,传说受到污染。相反,我希望颜色仅适用于背景而不会混合。我的另一个问题是:是否有一种方法可以在极坐标中工作?

有关可重现的示例,请参阅以下代码:

pies <- data_frame(pie = c(rep("hawaiian", 3), rep("pepperoni", 2)), 
                   fraction = c(c(0.3, 0.2, 0.5), c(0.4, 0.6)),
                   ingredient = c("cheese", "pineapple", "ham",
                                  "peperroni", "cheese"),
                   deepdish = c(rep(TRUE, 3), rep(FALSE, 2)))

p <- pies %>%
  ggplot() +
  geom_bar(aes(x = factor(1),
               y = fraction,
               fill = ingredient),
           width = 0.6,
           stat = "identity",
           position = "fill") +
  facet_wrap(~ pie) +
  geom_rect(mapping = aes(fill = deepdish),
            alpha = 0.1,
            xmin = -Inf, xmax = Inf,
            ymin=-Inf, ymax=Inf,
            show.legend = FALSE)

p
p + coord_polar(theta = "y")
r ggplot2 facet
2个回答
3
投票
pies <- data_frame(pie = c(rep("hawaiian", 3), rep("pepperoni", 2)), 
                   fraction = c(c(0.3, 0.2, 0.5), c(0.4, 0.6)),
                   ingredient = c("cheese", "pineapple", "ham",
                                  "peperroni", "cheese"),
                   deepdish = c(rep(TRUE, 3), rep(FALSE, 2)))
library(ggplot2)
library(dplyr)
p <- pies %>%
  ggplot() +
  geom_bar(aes(x = factor(1), y = fraction, fill = ingredient),
           width = 0.6, stat = "identity", position = "fill") +
  facet_wrap(~ pie) + coord_polar(theta = "y")

g <- ggplotGrob(p)
# Set manually the background color for each panel
g$grobs[[2]]$children[[1]]$children[[1]]$gp$fill <- "#88334466"
g$grobs[[3]]$children[[1]]$children[[1]]$gp$fill <- "#44338866"

library(grid)
grid.draw(g)

enter image description here


3
投票
library(egg)
library(grid)

pies <- data.frame(pie = c(rep("hawaiian", 3), rep("pepperoni", 2)), 
                   fraction = c(c(0.3, 0.2, 0.5), c(0.4, 0.6)),
                   ingredient = c("cheese", "pineapple", "ham",
                                  "peperroni", "cheese"))

dummy <- data.frame(x = 0, y = 0, 
                    pie = c("hawaiian","pepperoni"),
                    deepdish = c("green","yellow"), stringsAsFactors = FALSE)

p <-    ggplot(pies) +
  facet_wrap(~ pie) +
  geom_custom(data= dummy, mapping = aes(x = factor(0),
                            y = y,
                            data = deepdish), 
              grob_fun = function(x) rectGrob(gp=gpar(fill=x,col=NA)), inherit.aes = TRUE) +
  geom_bar(aes(x = factor(1),
               y = fraction,
               fill = ingredient),
           width = 0.6,
           stat = "identity",
           position = "fill") 

p + coord_polar(theta = "y")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.