首页 > 解决方案 > 在 `geom_bar()` 中找不到对象

问题描述

我想映射prop到条形图上的 y 轴,但我不断收到“找不到对象”错误。如何修复我的代码?谢谢!

dput(starwars_age)
structure(list(`Age Response` = c("> 60", "18-29", "30-44", "45-60"
), n = c(193L, 180L, 207L, 240L), prop = c(0.206196581196581, 
0.192307692307692, 0.221153846153846, 0.256410256410256)), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

starwars_age %>%
  mutate(`Age Response` = factor(`Age Response`, levels  = c("18-29","30-44","45-60","> 60"))) %>%
  ggplot(aes(x = `Age Response`))+
  geom_bar(aes(y = prop))

Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomBar, : object 'prop' not found

标签: rggplot2

解决方案


我们可以stat = 'identity'添加geom_bar

library(dplyr)
library(ggplot2)

starwars_age %>%
  mutate(`Age Response` = factor(`Age Response`, 
                          levels  = c("18-29","30-44","45-60","> 60"))) %>%
  ggplot(aes(x = `Age Response`)) + 
  geom_bar(aes(y = prop), stat = 'identity')

在此处输入图像描述


推荐阅读