R语言 两个变量的两个并排的隐藏条形图

ivqmmu1c  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(139)

我有一个像下面这样的数据框架...

Correlation_task_persistence <- c("0.40", "-0.46", "-0.24", "0.06")
Biv_A_task_persistence <- c("66%", "67%", "71%", "69%")
Biv_E_task_persistence  <- c("34%", "33%", "29%", "31%")
Correlation_activity <- c("0.33", "-0.59", "-0.10", "0.06")
Biv_A_activity <- c("40%", "65%", "70%", "97%")
Biv_E_activity <- c("60", "35%", "30%", "3%")
age <- c("30", "24", "18", "12")

df.new <- data.frame(Correlation_task_persistence, 
Biv_A_task_persistence,Biv_E_task_persistence,
 Correlation_activity, Biv_A_activity, Biv_E_activity, age )

我想复制下面的条形图,它代表了上面的数据框架中的数据(忽略图中的误差线)。将感谢任何帮助如何做到这一点。

4urapxun

4urapxun1#

library(dplyr)
library(tidyr)
library(ggplot2)

suppressWarnings(
  df.new %>% 
    mutate(across(Correlation_task_persistence:Biv_E_activity, 
                  ~if_else(as.numeric(gsub("%", "", .x)) > 1,
                           as.numeric(gsub("%", "", .x, fixed = TRUE))/100, 
                           as.numeric(.x)))) %>% 
    pivot_longer(-c(age, contains("Correlation"))) %>% 
    mutate(Correlation = if_else(grepl("task", name),
                                 Correlation_task_persistence, Correlation_activity),
           final_value = Correlation * value,
           name = gsub("_task", "", name)) %>% 
    tidyr::extract("name", c("var","group"), regex = "(.*)_([^_]+)$") %>% 
 ggplot(aes(x = age, y = final_value, fill = var)) +
  geom_col() +
  facet_wrap(~group)
)

数据:
df.new <- data.frame(Correlation_task_persistence = c("0.40", "-0.46", "-0.24", "0.06"),
                     Biv_A_task_persistence = c("66%", "67%", "71%", "69%"),
                     Biv_E_task_persistence  = c("34%", "33%", "29%", "31%"),
                     Correlation_activity = c("0.33", "-0.59", "-0.10", "0.06"),
                     Biv_A_activity = c("40%", "65%", "70%", "97%"),
                     Biv_E_activity = c("60", "35%", "30%", "3%"),
                     age = c("30", "24", "18", "12"))

相关问题