ggplot,饼图和facet_wrap中的不同半径

时间:2018-08-09 15:00:16

标签: r ggplot2 pie-chart

我想在不同的方面创建半径不同的饼图。 如何修改以下代码(产生相等的半径) 所以每个切片的总变量是th rasdius?

<?php print_r($_SERVER); ?>

2 个答案:

答案 0 :(得分:0)

您的问题有点不清楚。像这样吗?

library(tidyverse)
mydf <- data_frame(value = c(1:3, 1:3),
                   total = rep(c(10, 20), times = 3),
                   cond = rep(c("x", "y", "z"),times = 2),
                   group = rep(c("a", "b"), each = 3))
mydf %>% ggplot(aes(x = "", y = value, fill = cond)) +
    geom_bar(stat = "identity", width = 1) +
    facet_wrap(total ~ cond) +
    coord_polar("x")

1

答案 1 :(得分:0)

这是一个古老的问题,但是我想做同样的事情:饼的半径应随组的总数而变化。 首先,我使用geom_bar(position = "fill"),以便两个组栏堆叠到相同的高度。然后,我使用组总计作为宽度美学:ggplot(aes(x = total/2, width = total))。将总数的一半用于x美学可确保我们得到适当的馅饼而不是甜甜圈。 因此,以下代码对我有用,尽管我不确定其中有多少是hack,而不是适当的解决方案(如果将width美观移入geom_bar调用中,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)