RStudio 中的分组箱线图以获取相关数据

问题描述 投票:0回答:1

我有一个数据库,我需要将其放入分组箱线图图形中,我尝试了一些使用 R base 和 ggplot2 的东西,但它毫无价值,我不知道我是否必须重新组织数据库,或者也许有一个有效的代码。

This is the database I need a graph like this

phe <- data.frame(
horario= c("6:30","12:00","18:00","6:30","12:00","18:00","6:30","12:00","18:00"),
s1= c(7.48,7.49,7.29,7.35,7.47,7.27,7.41,7.99,8.07),
s2= c(7.61,7.55,7.45,7.29,7.32,7.34,7.21,7.27,7.29),
s3= c(8.02, 8.07, 7.84, 7.74, 7.83, 7.89, 7.17, 7.13, 7.17),
s4= c(8.41,9.42,9.18,7.87,10.45,9.85,8.25,10.51,10.15),
s5= c(8.24,10.56,9.81,7.69,9.17,8.27,6.96,9.59,9.16),
s6= c(7.74,10.39,9.93,7.88,10.4,9.56,8.06,9.96,9.39),
s7= c(8.41,10.7,10.19,8.43,10.72,9.95,8.08,10.19,9.11),
s8= c(8.2,10.97,10.22,8.17,9.59,9.16,8.17,9.23,8.27))

ggplot(phe, aes(x=horario, y=s1,s2,s3,s4,s5,s6,s7,s8, fill=horario)) +
geom_boxplot() +
facet_wrap(. ~ horario, scales = 'free_x')

我尝试使用这个数据框,但箱线图不是我需要的。 I got this but it jus shows 1 week and axes weren't ok

r database charts boxplot ggboxplot
1个回答
0
投票

当你写的时候,

aes(x=horario, y=s1,s2,s3,s4,s5,s6,s7,s8, fill=horario))
,这并没有按照你的想法去做。正如
ggplot2::aes()
文档所述:

x 和 y 美学的名称通常被省略,因为它们非常常见;所有其他美学都必须命名。

除了

s1
之外,
fill
之后的所有内容均未命名。它不会被传递给
geom_boxplot()
进行绘制。

关键是将数据以长格式保存:

phe_long <- tidyr::pivot_longer(
    phe,
    !horario,
    names_to = "week",
    names_transform = \(x) sub("s", "Week", x)
)

那么这只是造型的情况。这应该可以帮助您完成大部分工作:

ggplot(phe_long, aes(x = week, y = value, fill = week)) +
    geom_boxplot() +
    facet_wrap(. ~ horario, scales = "free_x", strip.position = "bottom") +
    theme_minimal(base_size = 14) +
    scale_fill_brewer(palette = "Dark2") +
    theme(
        axis.text.x = element_blank(),
        axis.title = element_blank(),
        strip.text = element_text(size = 16),
        panel.grid.major.x = element_blank(),
        legend.title = element_blank()
    )

© www.soinside.com 2019 - 2024. All rights reserved.