使用ggplot2绘制R因子变量柱状图的报错解决方法
解决ggplot2绘制因子变量柱状图的报错问题
报错原因
你遇到的Error: data must be a data frame...是因为ggplot2要求data参数必须传入数据框(或可被fortify()转换的对象),而你直接传入了单个因子变量chest,不符合要求。同时原代码还有两处问题:
aes(x="Chest_pain")是将x轴设为固定字符串,没有关联到因子的实际水平label=len中的len变量不存在,你需要调用统计后的频数数值
解决步骤
1. 将因子的统计结果转换为数据框
先通过table()获取因子各水平的频数,再转换为ggplot2可识别的数据框:
# 模拟你的chest因子变量(已有真实数据可跳过此步) chest <- factor(rep(1:4, times = c(23, 49, 84, 143))) # 将频数统计结果转为数据框 chest_df <- as.data.frame(table(chest)) # 重命名列名,方便后续绘图调用 colnames(chest_df) <- c("Chest_pain", "Count")
2. 使用ggplot2绘制柱状图
因为已经提前统计好频数,需要设置geom_bar(stat = "identity")避免ggplot重复统计;同时正确关联x轴变量和标签:
library(ggplot2) ggplot(data = chest_df, aes(x = Chest_pain, y = Count)) + geom_bar(stat = "identity", fill = "steelblue") + geom_text(aes(label = Count), vjust = -0.3, size = 3.5) + theme_minimal()
内容的提问来源于stack exchange,提问作者Dulce Montero
相关产品推荐
相关产品推荐

