r - 如何在多面图中勾勒出黑色条形图?

标签 r ggplot2 facet-wrap

我有一个类似于 Add stacked bar graphs inside faceted graphs 的情节. 我想移除网格线并用黑色勾勒出每个条形以及每个堆栈。

有办法吗?

library(tidyverse)
library(lubridate)
library(scales)


test <- tibble(
edu = c(rep("hs", 5), rep("bsc", 3), rep("msc", 3)),
sex = c(rep("m", 3), rep("f", 4), rep("m", 4)),
smoker = c("y", "n", "n", "y", "y", rep("n", 3), "y", "n", "n"))


test %>%
 count(sex, edu, smoker) %>%
group_by(sex) %>%
mutate(percentage = n/sum(n)) %>%
ggplot(aes(edu, percentage, fill = smoker)) +
geom_col() +
geom_text(aes(label = percent(percentage)),
 position = position_stack(vjust = 0.5)) +
facet_wrap(~sex) +
scale_y_continuous(labels = scales::percent) +
scale_fill_manual(values = c("#A0CBE8", "#F28E2B"))

最佳答案

使用主题()

您可以使用 geom_col(color = "black") 来绘制黑色轮廓,并使用 theme(panel.grid = element_blank()) 来移除网格线。

library(tidyverse)
library(lubridate)

test <- tibble(
  edu = c(rep("hs", 5), rep("bsc", 3), rep("msc", 3)),
  sex = c(rep("m", 3), rep("f", 4), rep("m", 4)),
  smoker = c("y", "n", "n", "y", "y", rep("n", 3), "y", "n", "n"))

test %>%
  count(sex, edu, smoker) %>%
  group_by(sex) %>%
  mutate(percentage = n/sum(n)) %>%
  ggplot(aes(edu, percentage, fill = smoker)) +
  geom_col(color = "black") +
  geom_text(aes(label = percent(percentage)),
            position = position_stack(vjust = 0.5)) +
  facet_wrap(~sex) +
  scale_y_continuous(labels = scales::percent) +
  scale_fill_manual(values = c("#A0CBE8", "#F28E2B")) +
  theme(panel.grid = element_blank())

reprex package 创建于 2022-08-05 (v2.0.1)

使用 theme_cowplot()

另一种删除网格线的方法是使用完善的程序包 cowplot

library(tidyverse)
library(lubridate)
library(scales)
library(cowplot)

test %>%
  count(sex, edu, smoker) %>%
  group_by(sex) %>%
  mutate(percentage = n/sum(n)) %>%
  ggplot(aes(edu, percentage, fill = smoker)) +
  geom_col(color = "black") +
  geom_text(aes(label = percent(percentage)),
            position = position_stack(vjust = 0.5)) +
  facet_wrap(~sex) +
  scale_y_continuous(labels = scales::percent) +
  scale_fill_manual(values = c("#A0CBE8", "#F28E2B")) +
  theme_cowplot()

reprex package 创建于 2022-08-05 (v2.0.1)

关于r - 如何在多面图中勾勒出黑色条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73253468/

相关文章:

r - 在ggplot2中组合条形图和折线图(双轴)

r - R 3.2.3 中的 ggplot2 : layers broken?

r - 如何从 R 中的 geoTIFF 获取像素值?

r - 将两组列名称传递给函数

r - 如何设置使用ggplot2绘制栅格图

R 映射 : how do I fill the regions?

r - 在 ggplot2 facet_wrap 图上添加彩色线条类型的主要图例

r - ggplot2 facet_grid 与 facet 标题

r - R 中的 Facet_Wrap 标签

r - 有条件地计算 2 个日期之间每个 ID 的唯一日期数