R语言 在ggplot2中为饼图的一个面设置背景色

9ceoxa92  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(249)

我试图创建一个包含三个方面的饼图。其中一个包含总体统计数据。因此,为了强调“总体”,我想在它后面放一个背景色。
以下是数据的外观

cat     action   pct
  <chr>   <chr>  <dbl>
1 All     No        34
2 All     Yes       66
3 Host    No        24
4 Host    Yes       76
5 Refugee No        38
6 Refugee Yes       62

这里是dput解构

> dput(a)
structure(list(cat = c("All", "All", "Host", "Host", "Refugee", 
"Refugee"), action = c("No", "Yes", "No", "Yes", "No", "Yes"), 
    pct = c(34, 66, 24, 76, 38, 62)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L), groups = structure(list(
    cat = c("All", "Host", "Refugee"), .rows = structure(list(
        1:2, 3:4, 5:6), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -3L), .drop = TRUE))

我以前试过添加一个 geomrect() 图层。通常这个方法可以在我没有使用 coord_polar() 的其他线图上使用。
下面是简化的代码:

a %>% 
  ggplot(aes("", pct, fill= action))+
  geom_rect(data = data.frame(cat="All"), aes(xmin = -Inf,xmax = Inf, ymin = -Inf,ymax = Inf,),
            fill='red',alpha = 0.2, inherit.aes = FALSE)+
  geom_bar(stat = "identity", position = "fill")+
  coord_polar(theta = "y", start = 0)+
  facet_wrap(~cat)+
  theme_solid()+
  guides(fill="none")

w51jfk4q

w51jfk4q1#

我不认为有一个简单的方法可以直接在ggplot中实现。矩形格和注解似乎不接受极坐标变换的无限限制,任何有限限制都会导致绘制圆形高亮区域。您也不能在theme中传递多个element_rect来样式化多个面板。
这就剩下两个广泛的选择:
1.分别生成图并将它们一起绘制在一个页面上
1.获取绘图的图形输出,并将适当的grob更改为具有适当填充颜色的rectGrob
实现第一个选项的一个简洁方法是使用dplyr::group_mappatchwork::wrap_plots

library(tidyverse)

a %>% 
  group_by(cat) %>%
  group_map(.keep = TRUE,
            ~ ggplot(.x, aes("", pct, fill = action)) +
    geom_bar(stat = "identity", position = "fill")+
    coord_polar(theta = "y", start = 0) +
    ggthemes::theme_solid() +
    guides(fill = "none") +
    theme(panel.background = element_rect(
            fill = if(all(.x$cat == 'All')) '#FF000032' else NA))) %>%
  patchwork::wrap_plots()

另一种选择是,如果出于某种原因,你需要使用facets,那么就像下面这样的grob hacking:

p <- a %>% 
  ggplot(aes("", pct, fill = action)) +
  geom_bar(stat = "identity", position = "fill") +
  coord_polar(theta = "y", start = 0) +
  facet_wrap(~cat) +
  ggthemes::theme_solid() +
  guides(fill = "none")

pg <- ggplotGrob(p)

new_background <- grid::rectGrob(gp = grid::gpar(fill = '#FF000032', col = NA))
panel1 <- pg$grobs[[which(pg$layout$name == 'panel-1-1')]]
panel1$children <- panel1$children
background <- grep('rect', sapply(panel1$children[[1]], names)$children)
panel1$children[[1]]$children[[background]] <- new_background
pg$grobs[[which(pg$layout$name == 'panel-1-1')]] <- panel1

grid::grid.newpage()
grid::grid.draw(pg)

相关问题