[英]How to bar plot answers per category in ggplot?
我有这样的小标题:
tibble(district = c(1, 5, 3, 5, 2, 7, 8, 1, 1, 2, 2, 4, 5, 6, 8, 6, 3),
housing = c(1, 1, 2, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 1, 3, 2))
现在,我想知道每个地区的住房类型。 由于每个地区的受访者人数有所不同,因此我想使用百分比。 基本上,我正在寻找两个地块。
1)一个条形图,其中住房类别的百分比以每区1条的形式可视化(因为它是百分比,因此所有条的高度均相等)。 2)每个区域的饼图,以及该特定区域的住房类别的百分比。
但是,我无法按照期望的方式对数据进行分组,一起计算它们的百分比。 如何制作这些图?
谢谢你!
试一下:
library(tidyverse)
library(ggplot2)
# original data
df <- data.frame(district = c(1, 5, 3, 5, 2, 7, 8, 1, 1, 2, 2, 4, 5, 6, 8, 6, 3),
housing = c(1, 1, 2, 1, 2, 2, 2, 1, 1, 2, 3, 2, 1, 1, 1, 3, 2))
# group by district
df <- df %>%
group_by(district) %>%
summarise(housing=sum(housing))
# make percentages
df <- df %>%
mutate(housing_percentage=housing/sum(df$housing)) %>%
mutate(district=as.character(district)) %>%
mutate(housing_percentage=round(housing_percentage,2))
# bar graph
ggplot(data=df) +
geom_col(aes(x=district, y=housing_percentage))
# pie chart
ggplot(data=df, aes(x='',y=housing_percentage, fill=district)) +
geom_bar(width = 1, stat = "identity", color = "white") +
coord_polar("y", start = 0) +
theme_void()
得出以下图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.