gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:39:26 33 4
gpt4 key购买 nike

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com