简体   繁体   English

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

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

I have a dataframe with ID as rows and several parameters for each ID as columns, among those parameters are columns of "weight at age 1", "weight at age 2", "weight at age 3" and "population".我有一个数据框,ID 为行,每个 ID 的几个参数为列,其中的参数是“1 岁时的体重”、“2 岁时的体重”、“3 岁时的体重”和“人口”列。 For each population, I would like to create its own scatter plot with age as x aes and weight as y aes, ideally, all population are layered on the same final graph.对于每个人口,我想创建自己的散点图,年龄为 x aes,体重为 y aes,理想情况下,所有人口都分层在同一个最终图上。 How do I do that?我怎么做? tnx!!天呐!!

an example of my data:我的数据示例:

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

I attempted to interpret your question.我试图解释你的问题。


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)

样本

You can reshape your dataframe into a long-format, and then use facet_wrap to create one plot for each 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)

Created on 2022-06-09 by the reprex package (v2.0.1)reprex 包(v2.0.1) 创建于 2022-06-09

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

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