向ggmosaic添加计数

向ggmosaic添加计数

本文介绍了向ggmosaic添加计数,这可以更简单吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ggmosaic软件包制作一个马赛克图,并添加计数,如下例所示.

I would like to make a mosaic plot using the ggmosaic package and add the counts as shown in the example below.

示例工作正常,但是我发现代码的结构非常难看.您对我如何改进代码以使其更具可重用性有任何建议吗?

The example sort of works, but I find the structure of the code quite ugly.Do you have any suggestions on how I can improve the code, to make it more reusable?

与通常使用ggplot2可以实现的情况相比,尤其需要将图形的早期版本存储在临时变量中似乎是错误的.

Especially the need for storing an early version of the plot in a temporary variable seems wrong compared to what usually can be achieved using 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-05-08.

Created on 2018-05-08 by the reprex package (v0.2.0).

推荐答案

我在纯ggplot2中制作了类似的图表,而没有使用ggmosaic软件包.不过,我不知道这是否足以满足您的用例:

I've previously made similar charts in pure ggplot2, without using the ggmosaic package. I don't know if this would be sufficient for your use case, though:

# 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"))

这篇关于向ggmosaic添加计数,这可以更简单吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 20:56