我有一个类似于 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/