我有一個資料框,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 |
uj5u.com熱心網友回復:
我試圖解釋你的問題。
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)

uj5u.com熱心網友回復:
您可以將資料框重塑為長格式,然后使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491420.html
