I want to use ggplot to make a histogram using percentages. I found this answer that gets me part of the way there.
我想用ggplot用百分比来绘制直方图。我找到了这个答案,让我找到了其中的一部分。
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)
Here is the output:
这是输出:
Unfortunately, you can see that the data labels are placed at the non-percentage locations and the bars are "smushed" down.
不幸的是,您可以看到数据标签被放置在非百分比位置,条形图被“弄脏”。
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)?
是否有一种方法可以更改stat_bin参数,使文本标签实际显示在百分比栏内或立即显示在百分比栏上(这样我的栏就不会被弄脏)?
Thank you!
谢谢你!
1 个解决方案
#1
2
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)
你还需要为标签设置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)
#1
2
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)
你还需要为标签设置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)