ggplot2 R:具有多个变量的百分比堆积条形图

时间:2021-06-09 17:05:34

标签: r ggplot2 data-visualization bar-chart

R 版本 4.0.5 (2021-03-31) 平台:x86_64-w64-mingw32/x64(64位) 运行于:Windows 10 x64(内部版本 19042)

我想创建一个百分比堆积条形图,包括 2 个组(区域、国际)和 4 个不同数值变量(地面低强度、地面高强度、常设低强度、常设高强度)的平均值。后面的变量以秒为单位表示每个时间段的持续时间。

我的数据是: dataset

下图代表了我想做的一个例子: Time-motion analysis description relative to total fight time, considering modalities and positions of actions Coswig, V. S., Gentil, P., Bueno, J. C., Follmer, B., Marques, V. A., & Del Vecchio, F. B. (2018). Physical fitness predicts technical-tactical and time-motion profile in simulated Judo and Brazilian Jiu-Jitsu matches. PeerJ, 6, e4851.

我已经阅读了很多指南并观看了很多 YT 教程,但其中大多数都使用了 2 个分类变量和 1 个数值变量,因此,它在我的情况下不起作用。

非常感谢任何帮助或指导。

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您提供可重现的示例并展示您做了什么以及哪里出了问题,您会在这里找到很多朋友。

数据

ds <- tribble(
    ~GROUP, ~GLI, ~GHI,~SLI, ~SHI,~GT,~ST,~EFFORT, ~PAUSE, ~HI, ~LI
    ,"REG", 158, 48, 26, 4, 205, 30, 235, 10, 51, 184
    ,"INT", 217, 62, 20, 1, 279, 21, 300, 11, 63, 237
)

{ggplot} 最适合处理长数据。这里 tidyr 是你的朋友和 pivot_longer()

ds <- ds %>% 
 pivot_longer(
         cols=c(GLI:SHI)          # wich cols to take
       , names_to = "intensity"   # where to put the names aka intensitites
       , values_to = "duration"   # where to put the values you want to plot
    ) %>% 
#-------------------- calculate the shares of durations per group
    group_by(GROUP) %>% 
    mutate(share = duration / sum(duration)
) 

这会给你一个这样的小标题:

# A tibble: 8 x 10
# Groups:   GROUP [2]
  GROUP    GT    ST EFFORT PAUSE    HI    LI intensity duration   share
  <chr> <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <chr>        <dbl>   <dbl>
1 REG     205    30    235    10    51   184 GLI            158 0.669  
2 REG     205    30    235    10    51   184 GHI             48 0.203  
3 REG     205    30    235    10    51   184 SLI             26 0.110  
4 REG     205    30    235    10    51   184 SHI              4 0.0169 
5 INT     279    21    300    11    63   237 GLI            217 0.723  
6 INT     279    21    300    11    63   237 GHI             62 0.207  
7 INT     279    21    300    11    63   237 SLI             20 0.0667 
8 INT     279    21    300    11    63   237 SHI              1 0.00333

最后一列为您提供类别和持续时间百分比,分组是使用 GROUP 变量完成的。 然后你可以用ggplot打印它。

ds %>%
    ggplot() + 
    geom_col(aes(x = GROUP, y = share, fill = intensity), position = position_stack())  + 
    scale_y_continuous(labels=scales::percent)

enter image description here

然后您可以“美化”情节,选择所需的主题、颜色、传说等。 希望这能让你开始!