【问题标题】:How to show percent labels on histogram bars using ggplot2如何使用ggplot2在直方图条上显示百分比标签
【发布时间】:2017-09-29 06:02:06
【问题描述】:

我已经看到很多关于将 y 轴上的计数转换为百分比的问题,但其中必须在条形图中。

我想在直方图中做类似的事情,但无法清楚地显示条形图上的标签。请告诉我哪里做错了。

x = runif(100, min = 0, max = 10)
data1 <- data.frame(x = x)

ggplot(aes(x = x), data = data1)+
geom_histogram(aes(y = (..count..)/sum(..count..)), bins = 10, breaks = 
seq(0,10,1), fill = "blue", col = "black")+
geom_text(aes(y = ((..count..)/sum(..count..)), 
            label = scales::percent((..count..)/sum(..count..))), 
        stat = "count", vjust = -10)+ 
scale_y_continuous(labels = scales::percent)

输出:

【问题讨论】:

    标签: r ggplot2 histogram


    【解决方案1】:

    使用带有中断和标签的scale_y_continous 将解决您的问题。

      data1 <- data.frame (x = runif(100, min = 0, max = 10))
    ggplot(aes(x=x), data1) + stat_bin(aes(y = ..count..)) 
    ggplot(data1, aes(x = x)) + geom_histogram(fill = "blue", col = "black")+ scale_y_continuous(breaks = seq(0,10,1),labels = paste(seq(0, 10, by = 1) / 100, "%", sep = ""))+geom_text(aes(y = (..count..),label =  scales::percent((..count..)/sum(..count..))), stat="bin",colour="green",vjust=2) 
    

    或者,您可以像这样指定要添加百分比的位置:

    geom_text(aes(y = (..count..)+0.5))
    

    当然,您也可以更改颜色。来自,

    stat="bin",colour="your prefer color "
    

    您还可以按如下方式更改箱的宽度:

    geom_histogram(fill = "blue", col = "black", binwidth = 0.5) 
    

    【讨论】:

    • 如何在每个条的顶部分别显示百分比?
    • 您仍然可以使用您的geom_text,它会起作用。稍微改一下:geom_text(aes(y = (..count..),label = your code)
    • 查看答案。希望对您的问题有所帮助。
    • 如何设置垃圾箱?我在 geom_histogram() 中设置了 bin 参数,但仍然使用bins = 30 获取stat_bin()。使用binwidth 选择更好的价值。
    • stat_bins() 只是给您的警告信息。你的数据很小。因此,请尝试使用一些 bin 值的大数据并查看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2019-02-04
    • 2019-03-12
    • 2021-09-12
    • 2022-12-14
    相关资源
    最近更新 更多