r - 如何使用 ggplot2 在直方图条上显示百分比标签

标签 r ggplot2 histogram

我看到很多关于将 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)

输出:

enter image description here

最佳答案

使用带有中断和标签的 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) 

enter image description here

enter image description here

heres the graph

关于r - 如何使用 ggplot2 在直方图条上显示百分比标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46482621/

相关文章:

r - PCA 使用行而不是列作为变量

r - 是否存在 table() 函数的一般逆函数?

R - 如何修改图例?

r - 使用多个 geom_point 图层指定指南图例美学

histogram - Tensorboard上直方图的含义

javascript - 如何将 R 包 (DT) 中的数据表包含到另一个 HTML 文件中

r - "Unexpected symbol"在 R

r - 结合系统发育树和 x,y 图

matlab - 这个 MATLAB 循环是否有更优雅的替代品?

javascript - 直方图的 X 轴值