ggplot2 具有多个因素的多行

ggplot2 multiple lines with multiple factors

我目前正在写我的硕士论文,我正在努力研究如何在 R 中制作多行和多因素的 ggplot。

我的数据是这样的

总而言之:我希望每周(第 1、2、3...12 周)在 y 轴和 x 轴上对温度(冷、暖、热)进行排序,每个参与者的红色组 1 和蓝色组 2。

我没有得到的是代码,我只能为每个轴插入一列。我将列更改为因子并已经对温度水平进行了排序。是否可以使用 ggplot 对其进行编码?

ggplot(data1, aes(x = Temperature 1st Week, y = ???, colour = Group, group = Code)) +
  geom_line() +
  ggtitle("Showering Temperature")               

来自瑞士的问候

诀窍是首先通过使用例如从宽格式转换为长格式或整洁格式来整理您的数据集。 tidy::pivot_longer。试试这个:

library(tidyverse)

set.seed(42)

temp_levels <- c("", "Sehr kalt (12 - 20\u00B0C)", 
                 "Kalt (21 - 26\u00B0C)", 
                 "Lauwarm (27 - 34\u00B0C)", 
                 "Warm (35 - 39\u00B0C)", 
                 "Sehr warm (\u00FCber 40\u00B0C)")


# Tidy data
data2 <- data1 %>% 
  # Convert from wide to long
  pivot_longer(starts_with("Duschtemperatur"), names_to = "Woche", values_to = "Duschtemperatur") %>%
  # Missings can be dropped with the following line of code. Just remove the `#' at the beginning`
  filter(Duschtemperatur != "", !is.na(Duschtemperatur)) %>% 
  mutate(
    # Tidying week labels: `str_extract` extracts the number of the week
    Woche = paste0("Woche ", str_extract(Woche, "\d+")),
    Gruppe = factor(Gruppe))

data2 %>% 
  ggplot(aes(Woche, Duschtemperatur, color = Gruppe, group = Code)) +
  geom_line() +
  # Add geom_jitter to check that all data is plot
  geom_jitter() +
  # Switched to labs instead of ggtitle, which allows for labelling title, 
  # axes, .. in one place
  labs(title = "Duschtemperatur", color = "Gruppe", x = NULL, y = NULL)

数据

# Example data
data1 <- data.frame(
  Code = c("TURN12", "AMMN17", "LKPG08", "LJRn05", "AGBD08", "IUGH20"),
  Gruppe = c(2, 1, 2, 2, 1, 2),
  StudentBasel = c("Ja", rep("Nein", 5)),
  Alter = c(50, 26, 19, 22, 24, 32), 
  Groesse = c(159, 164, 167, 180, 165, 168),
  Gewicht0W = c(70, 52, 54, 60, 49, 54),
  Gewicht12W = c(72, 50, rep(NA, 4)),
  Duschtemperatur0W = factor(temp_levels[c(5, 5, 5, 6, 5, 5)], levels = temp_levels),
  Duschtemperatur1W = factor(temp_levels[c(5, 5, 4, 1, 5, 5)], levels = temp_levels),
  Duschtemperatur2W = factor(temp_levels[c(5, 5, 1, 1, 5, 1)], levels = temp_levels)
)