我想使用 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))
由reprex 包(v0.2.0)于 2018 年 5 月 8 日创建。
这是使用提供的代码执行此操作的方法,但无需保存临时图。它利用 ggplotlast_plot
来访问绘图对象直到最近的“+”,并且还使用layer_data
, 而不是更简单地访问数据ggplot_build
。
library(tidyverse)
library(ggmosaic)
data <- tribble(~a, ~b,
1, 1,
1, 1,
1, 1,
1, 2,
2, 1,
2, 2,
3, 2)
data <- data %>%
mutate(across(c(a, b), as.factor))
ggplot(data) +
geom_mosaic(aes(x=product(b, a), fill=b)) +
geom_label(data = layer_data(last_plot(), 1) %>% filter(.wt > 0),
aes(x = (xmin + xmax) / 2,
y = (ymin + ymax) / 2,
label = .wt))
由reprex 包(v0.3.0)于 2020 年 7 月 5 日创建
这仍然是一个黑客,但它会为您省去分配临时情节的痛苦。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句