【问题标题】:Percentage labels in a bar plot条形图中的百分比标签
【发布时间】:2016-02-20 15:19:39
【问题描述】:

我想制作一个类似这样的图形:

我从这段代码开始:

library(ggplot2)
library(scales) #needed for labels=percent

var1 <- sample(0:20,78,replace = TRUE)

var2 <- cut(var1, breaks = seq(0,20,5),include.lowest = TRUE)
df<-as.data.frame(var2)

ggplot(df, aes(x= var2)) + 
      geom_bar(aes(y = ..prop..,group=1),fill="dodgerblue3")+
      scale_y_continuous(labels=percent)+
      labs(x = NULL,y = NULL)+
      theme(axis.ticks.x = element_blank(),
            axis.text = element_text(size=7)) 

但我无法将标签放在情节中。

我尝试关注this example

ggplot(df, aes(x= var2,  group=1)) + 
  geom_bar(aes(y = ..density..)) +
  geom_text(aes( label = format(100*..density.., digits=2, drop0trailing=TRUE),
                 y= ..density.. ), stat= "bin", vjust = -.5) +
  scale_y_continuous(labels=percent)

但是我得到了这个错误(我使用ggplot2-version 2.0.0):

错误:StatBin 需要一个连续的 x 变量,而 x 变量是离散的。也许你想要 stat="count"?

最后我用这段代码制作了情节:

per <- df %>% group_by(var2) %>% summarise(freq = n()/nrow(df))

ggplot(data=per, aes(x=var2,y=freq)) +
      geom_bar(stat="identity",fill="dodgerblue3")+
      geom_text(aes(label=percent(freq)),vjust=1.5,colour="white")+
      scale_y_continuous(labels=percent)+
      labs(x = NULL,y = NULL)+
      theme(axis.ticks.x = element_blank(),
            axis.text = element_text(size=7))

但是,是否可以在不需要 per 数据框的情况下直接在 ggplot 中制作 this example

【问题讨论】:

    标签: r ggplot2 label


    【解决方案1】:

    你可以试试这个,取自here并定制。

    ggplot(df, aes(factor(var2))) +
      geom_bar(fill="dodgerblue3")+
      labs(x = NULL,y = NULL)+
      stat_bin(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")),
               vjust = 1, geom = "text", position = "identity", color ="white")
    

    给予:

    编辑:

    在新的ggplot 2.0.X版本中,应该使用stat_count而不是stat_bin。来自help

    stat_count,计算每个 x 位置的病例数, 没有分箱。它适用于离散和连续 x 数据,而 stat_bin 只适用于连续的 x 数据。

       ggplot(df, aes(factor(var2))) +
          geom_bar(fill="dodgerblue3")+
          labs(x = NULL,y = NULL)+
          stat_count(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")),
                   vjust = 1, geom = "text", position = "identity", color ="white")
    

    【讨论】:

    • 谢谢。但它没有奏效。至少对我来说。我错过了一些东西,因为它对你有用。但是我已经尝试了您的代码,并且得到了相同的错误“错误:StatBin 需要连续的 x 变量,而 x 变量是离散的。也许你想要 stat="count"?'。我不知道我做错了什么。
    • @ChristianGonzalez-Martel 奇怪。试试 R/Rstudio(不保存工作区图像)然后再试一次?
    • 还是不行。也许问题出在 ggplot2 的版本上。我用的是 2.0.0。你用的是同款吗?
    • @ChristianGonzalez-Martel 我运行的是旧版本。已更新,现在遇到与您相同的错误!漏洞?!请将您的所有版本信息添加到您的问题中,并提及它适用于 ggplot-version 1.X
    • @ChristianGonzalez-Martel 我发现了问题并将其添加到我的答案中
    猜你喜欢
    • 2021-11-27
    • 2020-10-12
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多