R语言 'geom_text()'中的错误:geom_text()'需要以下缺失的美学特性:x和y

lx0bsm1f  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(537)

我想创建一个柱状图,在这些柱状图上有图例。图例代表每天的平均睡眠时间。

ggplot(average_sleep_per_day) +
  geom_col(aes(x = reorder(day, average_sleep), y = average_sleep, fill = average_sleep))  +
            labs(title = "average_sleep_per_day") +
            theme_classic() +
            theme(panel.background = element_blank(),
                   plot.title = element_text(hjust = 0.5, size=10, face = "bold")) +
            geom_text(aes(label = round(average_sleep, 1)),
            position = position_stack(vjust = 1.02))

我的数据:

average_sleep_per_day <- structure(
  list(
    day = c("Dimanche", "Jeudi", "Lundi"),
    average_sleep = c(7.54575757575758, 6.68828125, 6.99166666666667)
  ),
  row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame")
)
nlejzf6q

nlejzf6q1#

正如我在评论中提到的,问题是xygeom_col中被指定为局部美学。要解决这个问题,可以像下面的代码一样将它们移动到ggplot()中,或者也可以将它们添加到geom_text中的aes()中,从而使它们成为全局美学。

average_sleep_per_day <- structure(list(day = c("Dimanche", "Jeudi", "Lundi"), average_sleep = c(7.54575757575758, 6.68828125, 6.99166666666667)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))

library(ggplot2)

ggplot(average_sleep_per_day, aes(x = reorder(day, average_sleep), y = average_sleep)) +
  geom_col(aes(fill = average_sleep)) +
  labs(title = "average_sleep_per_day") +
  theme_classic() +
  theme(
    panel.background = element_blank(),
    plot.title = element_text(hjust = 0.5, size = 10, face = "bold")
  ) +
  geom_text(aes(label = round(average_sleep, 1)),
    position = position_stack(vjust = 1.02)
  )

相关问题