带百分比和百分比的ggplot直方图*标签* [英] ggplot histogram with % and percentage *labels*

查看:273
本文介绍了带百分比和百分比的ggplot直方图*标签*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ggplot使用百分比制作直方图.我找到了 此答案 ,这使我成为其中的一部分.

I want to use ggplot to make a histogram using percentages. I found this answer that gets me part of the way there.

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

However, I also want to place a label at the top of each histogram bar showing the actual percentage.

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

Here is my code and a link to the output:

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)

以下是输出:

不幸的是,您可以看到数据标签被放置在非百分比位置,并且条形被压扁"了.

Unfortunately, you can see that the data labels are placed at the non-percentage locations and the bars are "smushed" down.

是否可以更改stat_bin参数,以使文本标签实际显示在百分比条的内部或顶部(这样就不会弄脏我的条)?

Is there a way to change the stat_bin parameters so that the text labels actually show up inside or immediately on top of the percentage bars (so that my bars aren't smushed)?

谢谢!

推荐答案

您还要设置标签的y值(并确保您使用的是相同的垃圾箱)酒吧)

You'll want to just set the y values for your labels as well (and also make sure you're using the same bins are you are for the bars)

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)

这篇关于带百分比和百分比的ggplot直方图*标签*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆