mid*_*iby 9 r ggplot2 ggmosaic
我想使用 ggmosaic 包制作马赛克图并添加计数,如下例所示。
该示例有点工作,但我发现代码的结构非常难看。您对我如何改进代码以使其更具可重用性有什么建议吗?
特别是与通常使用 ggplot2 可以实现的相比,需要将绘图的早期版本存储在临时变量中似乎是错误的。
library(tidyverse)
library(ggmosaic)
#> Indlæser krævet pakke: productplots
#>
#> Vedhæfter pakke: 'ggmosaic'
#> De følgende objekter er maskerede fra 'package:productplots':
#>
#> ddecker, hspine, mosaic, prodcalc, spine, vspine
data <- tribble(~a, ~b,
1, 1,
1, 1,
1, 1,
1, 2,
2, 1,
2, 2,
3, 2)
p <- ggplot(data) +
geom_mosaic(aes(x=product(b, a), fill=as.factor(b)))
p +
geom_label(data = ggplot_build(p)$data %>% as.data.frame() %>% filter(.wt > 0),
aes(x = (xmin + xmax)/2,
y = (ymin + ymax)/2,
label = .wt))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.0)于 2018 年 5 月 8 日创建。
我之前在纯 ggplot2 中制作了类似的图表,没有使用 ggmosaic 包。不过,我不知道这是否足以满足您的用例:
# data manipulation
data %>%
group_by(a, b) %>%
summarise(n = n()) %>%
mutate(x.width = sum(n)) %>%
# simulate mosaic plot
ggplot(aes(x = factor(a), y = n)) +
geom_col(aes(width = x.width, fill = factor(b)),
colour = "white", size = 1, position = position_fill(reverse = TRUE)) +
geom_label(aes(label = n),
position = position_fill(vjust = 0.5)) +
facet_grid(~ a, space = "free", scales = "free", switch = "x") +
# cosmetic tweaks
scale_x_discrete(name = "a") +
scale_y_continuous(labels = scales::percent) +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.y = element_blank(),
strip.background = element_blank(),
panel.spacing = unit(0, "pt"))
Run Code Online (Sandbox Code Playgroud)
小智 5
这可以使用包的内置标签功能通过一行代码来完成ggmosaic。
为此,我们只需添加图层geom_mosaic_text():
data <- tribble(~a, ~b,
1, 1,
1, 1,
1, 1,
1, 2,
2, 1,
2, 2,
3, 2) %>%
mutate(across(c(a, b), as.factor))
ggplot(data) +
geom_mosaic(aes(x=product(b, a), fill=b)) +
geom_mosaic_text(aes(x = product(b, a), label = after_stat(.wt)), as.label=TRUE)
Run Code Online (Sandbox Code Playgroud)