在这种情况下,我的ggplot2代码中y的geom_text美学应该是什么?

时间:2019-04-12 05:25:22

标签: r ggplot2 geom-text

我在ggplot2中运行以下RStudio代码:

p2 <- ggplot(subset(df1,LEVEL %in% c("FM")),aes(x=los_group)) +
    ggtitle("FM: % of Respondents by Length of Service") + xlab("LOS Group") +
    geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5, fill="steelblue") + 
    ylab("Percentage") +
    geom_text(position=position_dodge(width=0.9), hjust= 1.5, 
    vjust=0.5, angle = 90, color="white", fontface="bold", size=6)+
    coord_flip() + 
    theme_minimal()

p2

我想在条形图(顶端)中插入百分比值(带有%符号)。我一直坚持在y代码中指定geom_text美学。

当前,我收到以下错误消息:

Error: geom_text requires the following missing aesthetics: y, label

1 个答案:

答案 0 :(得分:1)

以下是使用标准数据的示例,因为我们没有您的df1

当我在多个地方使用计算时,通常最简单的方法是在ggplot之前进行计算并将其输入,这将被解释为ggplot调用的第一个(即数据)项。

library(tidyverse)

# Calculate share of counts per cylinder, and pipe that into ggplot
mtcars %>%
  count(cyl = as.factor(cyl)) %>%
  mutate(share = n / sum(n)) %>%

  # Declare global x, y, and label mapping. If not specifically specified
  #   in subsequent `geoms`, they will adopt these. 
  ggplot(aes(x=cyl, y = share, label = scales::percent(share, accuracy = 1))) +
  ggtitle("FM % of Respondents by Length of Service") + 
  xlab("LOS Group") +
  geom_col(width = 0.8, fill="steelblue") + 
  ylab("Percentage") +
  geom_text(position=position_dodge(width=0.9), hjust= 0.5, 
            vjust=-0.5, angle = 90, color="white", fontface="bold", size=6) +
  coord_flip() + 
  theme_minimal()

enter image description here