我想使用 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)
这是输出:
不幸的是,您可以看到数据标签位于非百分比位置,并且条形被“弄脏”了。
有没有办法更改 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/