提问人:Maya Eldar 提问时间:6/9/2022 更新时间:6/9/2022 访问量:134
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,理想情况下,所有总体都分层在同一个最终图上。 我该怎么做? tnx!!
我的数据示例:
编号 | 人口 | 1岁时体重 | 2岁时体重 | 3岁时体重 |
---|---|---|---|---|
1 | 一个 | 13.37 | 14.15 | 17.36 |
2 | 一个 | 5.19 | 15.34 | 那 |
3 | B | 7.68 | 6.92 | 19.42 |
4 | B | 6.96 | 15.12 | 36.39 |
5 | C | 10.35 | 8.86 | 26.33 |
答:
1赞
Susan Switzer
6/9/2022
#1
我试图解释你的问题。
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)
评论
0赞
Maya Eldar
6/12/2022
谢谢!我做了一些改动:......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), color=POPULATION)+ geom_smooth()
1赞
Jonathan
6/9/2022
#2
您可以将数据框重整为长格式,然后用于为每个总体创建一个绘图: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 创建
评论