我想制作一個看起來像下面所附的圖,據我所知,可以使用包中的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)。非常感謝!
uj5u.com熱心網友回復:
首先,我們需要重塑資料并預先計算每個主題的組均值。
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 包(v2.0.1)于 2021 年 10 月 22 日創建
還有香草 ggplot2 方法:
ggplot(df2, aes(x = name, y = value, fill = name))
geom_col(width = 1)
facet_wrap(~ Group)
coord_polar(theta = "x")

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335787.html
