帮我修改以下代码,使它可以正确运行:gss_cat %>% filter(!is.na(age)) %>% mutate(age_group = case_when( age <= 45 ~ "youth", age >= 46 & age <= 69 ~ "middle_aged", age >= 70 ~ "old_people" )) %>% mutate(age_group = fct_relevel(as.factor(age_group), "youth", "middle_aged", "old_people")) %>% group_by(year, age_group, race) %>% summarise(n = n()) %>% pivot_wider(names_from = age_group, values_from = n) %>% mutate(youth_prop = youth / (youth + middle_aged + old_people)) %>% pivot_longer(cols = youth_prop, names_to = "age_group", values_to = "prop") %>% separate(age_group, into = c("age_group", "prop_type"), sep = "_") %>% pivot_wider(names_from = prop_type, values_from = prop) %>% ggplot(aes(x = year, y = youth_prop, group = race, color = race)) + geom_line() + labs(x = "年份", y = "青年人比例", title = "不同种族青年人比例随时间变化趋势") + theme_minimal()
时间: 2024-03-17 20:45:58 浏览: 59
这段代码看起来是对一个数据集进行处理并使用 `ggplot2` 包绘制一条线图,但是缺少数据集名称。你可以将该代码与你的数据集结合使用,例如:
```
your_data %>%
filter(!is.na(age)) %>%
mutate(age_group = case_when(
age <= 45 ~ "youth",
age >= 46 & age <= 69 ~ "middle_aged",
age >= 70 ~ "old_people"
)) %>%
mutate(age_group = fct_relevel(as.factor(age_group), "youth", "middle_aged", "old_people")) %>%
group_by(year, age_group, race) %>%
summarise(n = n()) %>%
pivot_wider(names_from = age_group, values_from = n) %>%
mutate(youth_prop = youth / (youth + middle_aged + old_people)) %>%
pivot_longer(cols = youth_prop, names_to = "age_group", values_to = "prop") %>%
separate(age_group, into = c("age_group", "prop_type"), sep = "_") %>%
pivot_wider(names_from = prop_type, values_from = prop) %>%
ggplot(aes(x = year, y = youth_prop, group = race, color = race)) +
geom_line() +
labs(x = "年份", y = "青年人比例", title = "不同种族青年人比例随时间变化趋势") +
theme_minimal()
```
在这个代码中,`your_data` 是你的数据集,你需要将其替换为你真正使用的数据集的名称。此外,你还需要确保你已经正确加载了 `ggplot2` 包。
阅读全文