Show percent % instead of counts in charts of categorical variables

前端 未结 8 2499
梦如初夏
梦如初夏 2020-11-22 06:06

I\'m plotting a categorical variable and instead of showing the counts for each category value.

I\'m looking for a way to get ggplot to display the perc

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 06:36

    If you want percentages on the y-axis and labeled on the bars:

    library(ggplot2)
    library(scales)
    ggplot(mtcars, aes(x = as.factor(am))) +
      geom_bar(aes(y = (..count..)/sum(..count..))) +
      geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
      scale_y_continuous(labels = percent) +
      labs(title = "Manual vs. Automatic Frequency", y = "Percent", x = "Automatic Transmission")
    

    When adding the bar labels, you may wish to omit the y-axis for a cleaner chart, by adding to the end:

      theme(
            axis.text.y=element_blank(), axis.ticks=element_blank(),
            axis.title.y=element_blank()
      )
    

提交回复
热议问题