我想使用ggplot2作图,以便有条形图显示每种城市/农村环境(方面)中人们的度数(条形)。我做到了。
现在,我想为每个方面增加具有各种资格的人员比例。我使用下面的代码得到的是整个人口的百分比。
如何更改代码,以便在每个方面内计算百分比?
这是我使用的数据集中有1,000行的示例:link。
library(ggplot2)
library(scales)
# plot urban/rural by degree in facets
myplot <- ggplot(data = si
,aes(DEGREE)
)
myplot <- myplot + geom_bar()
myplot <- myplot + labs(title = "Degree by Urban/Rural", y = "Percent", x = "DEGREE")
myplot <- myplot + geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25)
myplot <- myplot + facet_wrap(~URBRURAL)
myplot <- myplot + theme(axis.text.x = element_text(angle = 20, hjust = 1))
myplot
在绘制数据之前,您始终可以转换数据以计算所需的数据。我还添加了一些调整(栏顶部的标签,x轴上的字符串换行,轴限制和标签)。
library(dplyr)
library(ggplot2)
library(stringr)
plot_data <- df %>%
group_by(URBRURAL, DEGREE) %>%
tally %>%
mutate(percent = n/sum(n))
ggplot(plot_data, aes(x = DEGREE, y = percent)) +
geom_bar(stat = "identity") +
geom_text(aes(label = percent(percent)), vjust = -0.5) +
labs(title = "Degree by Urban/Rural", y = "Percent", x = "DEGREE") +
scale_y_continuous(labels = percent, limits = c(0,1)) +
scale_x_discrete(labels = function(x) str_wrap(x, 10)) +
facet_wrap(~URBRURAL)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句