这是一个老问题,但我想做同样的事情:饼图半径应随组总数而变化。
首先,我使用geom_bar(position = "fill") 使两个组条堆叠到相同的高度。然后我使用组总数作为宽度美学:ggplot(aes(x = total/2, width = total))。将总数的一半用于 x 美学确保我们得到合适的馅饼而不是甜甜圈。
所以,下面的代码对我有用,虽然我不确定这有多少是一个黑客而不是一个正确的解决方案(如果我们将width 美学移动到geom_barcall 中,ggplot 会发出警告:geom_bar(aes(width = total)) )。
library(tidyverse)
mydf <- tibble(group = rep(c("group a", "group b"), each = 3),
cond = rep(c("x", "y", "z"), times = 2),
value = c(1, 2, 3, 2, 4, 6)) %>%
group_by(group) %>%
add_tally(value, name = "total") %>%
ungroup() %>%
mutate(label = sprintf("total = %d", total)) %>%
print()
#> # A tibble: 6 x 5
#> group cond value total label
#> <chr> <chr> <dbl> <dbl> <chr>
#> 1 group a x 1 6 total = 6
#> 2 group a y 2 6 total = 6
#> 3 group a z 3 6 total = 6
#> 4 group b x 2 12 total = 12
#> 5 group b y 4 12 total = 12
#> 6 group b z 6 12 total = 12
mydf %>% ggplot(aes(x = total/2, y = value, fill = cond, width = total)) +
geom_bar(stat = "identity", position = "fill", color = "white") +
facet_wrap(~ group + label, strip.position = "bottom") +
coord_polar("y", start = 0, direction = -1) +
theme_bw(base_size = 12) +
theme(axis.title = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank(),
panel.grid = element_blank(),
panel.border = element_blank(),
legend.title = element_text(size = 14),
strip.background = element_rect(fill = NA, colour = NA),
strip.text = element_text(size = 16))
由reprex package (v0.3.0) 于 2020-02-13 创建
为了更好地理解其工作原理,我们可以删除 coord_polar() 和 theme() 调用以查看底层条形图:
mydf %>% ggplot(aes(x = total/2, y = value, fill = cond, width = total)) +
geom_bar(stat = "identity", position = "fill", color = "white") +
facet_wrap(~ group + label, strip.position = "bottom") +
theme_bw(base_size = 12)