繁体   English   中英

R:如何创建一个以 3 列作为一个连续 x 因子的散点图?

[英]R: how to create a scatter plot with 3 columns as one continuance x factor?

我有一个数据框,ID 为行,每个 ID 的几个参数为列,其中的参数是“1 岁时的体重”、“2 岁时的体重”、“3 岁时的体重”和“人口”列。 对于每个人口,我想创建自己的散点图,年龄为 x aes,体重为 y aes,理想情况下,所有人口都分层在同一个最终图上。 我怎么做? 天呐!!

我的数据示例:

ID 人口 1岁体重 2岁体重 3岁体重
1 一个 13.37 14.15 17.36
2 一个 5.19 15.34 不适用
3 7.68 6.92 19.42
4 6.96 15.12 36.39
5 C 10.35 8.86 26.33

我试图解释你的问题。


library(tidyverse)
#pivot data into long format

df <- data.frame(
  stringsAsFactors = FALSE,
                ID = c(1L, 2L, 3L, 4L, 5L),
        POPULATION = c("A", "A", "B", "B", "C"),
   weight.at.age.1 = c(13.37, 5.19, 7.68, 6.96, 10.35),
   weight.at.age.2 = c(14.15, 15.34, 6.92, 15.12, 8.86),
   weight.at.age.3 = c(17.36, NA, 19.42, 36.39, 26.33)
) %>% 
  pivot_longer(cols = weight.at.age.1:weight.at.age.3, 
               names_to = 'age', 
               values_to = 'weight') %>% 
  mutate(age = str_remove(age, 'weight.at.age.'))

#plot data
ggplot(data = df, 
       mapping = aes(x = age, 
                     y = weight))+
  geom_point()+
  facet_wrap(~POPULATION)

样本

您可以将数据框重塑为长格式,然后使用facet_wrap为每个人口创建一个图:

library(tidyverse)

df <- expand_grid(population = LETTERS[1:3], age = 1:10, id = 1:3) %>% mutate(weight = rgamma(n(), 1) * 10) %>% 
  pivot_wider(names_from = age, names_prefix = "weight at ", values_from = weight) %>%
  mutate(id = row_number())

df_long <- df %>% pivot_longer(starts_with("weight at "), names_to = "age", values_to = "weight") %>% 
  mutate(age = as.integer(str_extract(age, "\\d+")))

ggplot(df_long, aes(age, weight)) + geom_point() + facet_wrap(~ population)

reprex 包(v2.0.1) 创建于 2022-06-09

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM