r - 带有 % 和百分比 *labels* 的 ggplot 直方图

标签 r ggplot2 label histogram

我想使用 ggplot 制作一个使用百分比的直方图。我找到了 this answer 这让我参与其中。

但是,我还想在每个直方图条的顶部放置一个标签,以显示实际百分比。

这是我的代码和输出链接:

p <- ggplot(mtcars, aes(x = hp)) +  
        geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
        ## scale_y_continuous(labels = percent_format()) #version 3.0.9
        scale_y_continuous(labels = percent) #version 3.1.0
p <- p + stat_bin(aes(label=round((..count..)/sum(..count..),2)), geom="text", size=4)
plot(p)

这是输出:image

不幸的是,您可以看到数据标签位于非百分比位置,并且条形被“弄脏”了。

有没有办法更改 stat_bin 参数,使文本标签实际显示在百分比条的内部或紧挨着百分比条的顶部(这样我的条就不会被弄脏)?

谢谢!

最佳答案

您还需要为标签设置 y 值(并确保您使用与条形图相同的容器)

library(scales)
p <- ggplot(mtcars, aes(x = hp)) +  
        geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
        scale_y_continuous(labels = percent_format()) #version 3.0.9
        ##scale_y_continuous(labels = percent) #version 3.1.0
p <- p + stat_bin(aes(y=(..count..)/sum(..count..), 
    label=round((..count..)/sum(..count..),2)), 
    geom="text", size=4, binwidth = 25, vjust=-1.5)
plot(p)

关于r - 带有 % 和百分比 *labels* 的 ggplot 直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27593888/

相关文章:

r - Plotly:如何根据值指定符号和颜色?

r - plot.lm() : extracting numbers labelled in the diagnostic Q-Q plot

r - 自定义轴标签

swift - 我无法在 Swift 3 中使用计时器更改 label.text

r - 基于唯一匹配条件的过滤

r - 在 stat_smooth 之上更改图例中 geom_point 的 alpha 级别

r - 使用 qqmath 或 dotplot : How to make it look fancy? 绘制来自 lmer(lme4 包)的随机效应

d3.js - 如何在 d3.js 中的文本中放置一个断点

c# - 标签图像模式拉伸(stretch)

r - 如何在 R 中用因子值(如 y)做 ggplot barplot?