首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >多因素ggplot2多行

多因素ggplot2多行
EN

Stack Overflow用户
提问于 2020-03-11 14:36:27
回答 1查看 138关注 0票数 0

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

我的数据是这样的

每个参与者的,2...

  • Temperature

  • 代码: XXX,YYY,ZZZ

  • 组: 1,2,1第1周:冷,温,Hot...
  • Temperature第2周:冷,暖,热.
  • 最多12周

总结:我想让温度排序(冷,温暖,热)在y轴和x轴每周(第1,2,3周).12)每个参与者的颜色为红色组1和蓝色组2。

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

代码语言:javascript
运行
复制
ggplot(data1, aes(x = Temperature 1st Week, y = ???, colour = Group, group = Code)) +
  geom_line() +
  ggtitle("Showering Temperature")               

瑞士的问候

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-13 10:31:15

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

代码语言:javascript
运行
复制
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)

数据

代码语言:javascript
运行
复制
# 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)
) 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60638534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档