0

我想制作一个看起来像下面附上的图,据我了解,可以使用包中的geom_arc_bar()函数来实现ggforce在此处输入图像描述

df <- data.frame(English = sample(1:100,10),
                Math = sample(1:100,10),
                History = sample(1:100,10),
                Science = sample(1:100,10),
                Group = rep(c("A","B","C","D","E"),each=2))

给定一个示例数据框,我将如何处理这个问题,其中每个条形图是每个组的平均值,因此对于这个示例 df,每个组(A、B、C、D、E)和每个圆应该有 5 个圆弧线中是否有 4 个科目分数的平均值?其他绘图方法也很好(不一定必须是 by ggforce)。非常感谢!

4

1 回答 1

1

首先,我们需要重塑数据并预先计算每个主题的组均值。

library(ggplot2)
library(ggforce)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- data.frame(English = sample(1:100,10),
                 Math = sample(1:100,10),
                 History = sample(1:100,10),
                 Science = sample(1:100,10),
                 Group = rep(c("A","B","C","D","E"),each=2))

# Reshape and calculate group means
df2 <- df %>% 
  tidyr::pivot_longer(-Group) %>%
  group_by(Group, name) %>%
  summarise(value = mean(value), .groups = "keep")

接下来我们需要定义一个函数和一些常量来帮助我们生成绘图。

# Map discrete values to continuous
helper <- function(x) {match(x, sort(unique(x)))}

# Helper values
nsubjects <- length(unique(df2$name))
tau <- 2 * pi
arc_part <- tau / nsubjects
circle_size <- 1
circle_spacing <- 0.1
circle_offset <- 0.8 * circle_size

最后,我们可以ggforce::geom_arc_bar()用来绘制数据。

ggplot(df2) +
  # Outline circle
  geom_arc(
    data = ~ subset(.x, !duplicated(Group)),
    aes(x0 = (helper(Group) - 1) * 2 * (circle_size + circle_spacing), 
        y0 = 0, r = circle_size, start = 0, end = tau)
  ) +
  # Subject quadrants
  geom_arc_bar(
    aes(x0 = (helper(Group) - 1) * 2 * (circle_size + circle_spacing),
        y0 = 0, r0 = 0,
        r = value * circle_offset / max(value),
        start = (helper(name) - 1) * arc_part,
        end   = helper(name) * arc_part,
        fill  = name)
  ) +
  coord_equal()

reprex 包于 2021-10-22 创建(v2.0.1)

还有香草 ggplot2 方法:

ggplot(df2, aes(x = name, y = value, fill = name)) +
  geom_col(width = 1) +
  facet_wrap(~ Group) +
  coord_polar(theta = "x")

于 2021-10-22T11:17:26.160 回答