有两个表格da1、da2,表中都有属性sg(代表身高)、tz代表体重,请设计R语言代码实现bmi的饼图(分为“偏低”(bmi<18)、“正常”(18<=bmi<24)、“超重”(bmi>=24)),前两行代码为da1 <- read_excel("D:/R/sj_1.xlsx") da2 <- read_excel("D:/R/sj_2.xlsx")
时间: 2024-03-03 10:49:05 浏览: 88
可以使用以下代码实现:
```
library(dplyr) # 加载dplyr包
library(ggplot2) # 加载ggplot2包
# 读取数据
da1 <- read_excel("D:/R/sj_1.xlsx")
da2 <- read_excel("D:/R/sj_2.xlsx")
# 合并数据
da <- bind_rows(data.frame(type = "da1", da1), data.frame(type = "da2", da2))
# 计算BMI指数
da <- da %>% mutate(bmi = tz / (sg / 100) ^ 2)
# 将BMI指数按照偏低、正常、超重分类
da <- da %>% mutate(bmi_type = case_when(bmi < 18 ~ "偏低",
bmi >= 18 & bmi < 24 ~ "正常",
bmi >= 24 ~ "超重"))
# 绘制饼图
ggplot(da, aes(x = "", fill = bmi_type)) +
geom_bar(width = 1, stat = "count") +
coord_polar(theta = "y") +
facet_wrap(~type) +
theme_void() +
theme(legend.position = "bottom")
```
这段代码首先加载了dplyr和ggplot2包,然后读取了两个表格,并将它们合并为一个数据框。接着,根据身高和体重计算了BMI指数,并将BMI指数按照分类规则分为偏低、正常和超重三类。最后,使用ggplot2包绘制了饼图。其中,`facet_wrap(~type)`的作用是将不同的表格分别绘制在不同的子图中。
阅读全文
相关推荐















