【问题标题】:ggplot2 multiple lines with multiple factorsggplot2多行多因素
【发布时间】:2020-03-11 14:36:27
【问题描述】:

我目前正在写我的硕士论文,我正在努力解决如何在 R 中制作具有多行和多个因素的 ggplot。

我的数据是这样的

  • 每位参与者的代码:XXX、YYY、ZZZ
  • 组:1、2、1、2...
  • 第 1 周的温度:冷、暖、热......
  • 第 2 周温度:冷、暖、热......
  • 长达 12 周

总结一下:我希望每周(第 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")               

来自瑞士的问候

【问题讨论】:

  • 嗨!了解更多有关数据结构的信息以提供答案会很有帮助。例如,您是否有要在 y 轴上绘制的连续变量,或者只是三个温度水平?您能否将head(data1)str(data1) 的输出添加到您的问题中?我怀疑答案将涉及从宽到长操纵您的数据 [uc-r.github.io/tidyr] 但很难说没有更多信息。

标签: r ggplot2 factors


【解决方案1】:

诀窍是首先通过将宽格式转换为长格式或整洁格式来整理数据集,例如使用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)
) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多