[英]R ggplot2 create a pyramid plot
根據下面的代碼,我正在嘗試通過遵循此問題的第三個答案來創建pyramid plot
:
但是,該代碼返回一個堆疊列 plot 而不是一個金字塔 plot,x 軸左側有一個性別。
我怎樣才能解決這個問題?
數據+代碼:
library(tidyverse)
library(janitor)
library(lemon)
pop = structure(list(age_group = c("< 5 years", "5 - 9", "10 - 14",
"15 - 19", "20 - 24", "25 - 29", "30 - 34", "35 - 44",
"45 - 54", "55 - 64", "65 - 74", "75 - 84", "85 +"),
males = c(6, 6, 7, 6, 7, 7, 8, 17, 15, 11, 6, 3, 1), females = c(6,
5, 6, 6, 6, 7, 7, 16, 15, 12, 7, 4, 2)), row.names = c(NA,
-13L), spec = structure(list(cols = list(`AGE GROUP` = structure(list(), class = c("collector_character",
"collector")), MALES = structure(list(), class = c("collector_double",
"collector")), FEMALES = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x0000029a145331e0>, class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"))
# Draw a pyramid plot
pop_df = pop %>% select(age_group,
males,
females) %>%
gather(key = Type, value = Value, -c(age_group))
ggplot(data = pop_df,
mapping = aes(x = ifelse(test = Type == "male", yes = -Value, no = Value),
y = age_group, fill = Type)) +
geom_col() +
scale_x_symmetric(labels = abs) +
labs(x = "Population")
當前 output:
您可以將一個性別設為負值以創建金字塔 plot 並使用兩個geom_bar
,每個性別一個,如下所示:
library(tidyverse)
library(janitor)
library(lemon)
pop = structure(list(age_group = c("< 5 years", "5 - 9", "10 - 14",
"15 - 19", "20 - 24", "25 - 29", "30 - 34", "35 - 44",
"45 - 54", "55 - 64", "65 - 74", "75 - 84", "85 +"),
males = c(6, 6, 7, 6, 7, 7, 8, 17, 15, 11, 6, 3, 1), females = c(6,
5, 6, 6, 6, 7, 7, 16, 15, 12, 7, 4, 2)), row.names = c(NA,
-13L), spec = structure(list(cols = list(`AGE GROUP` = structure(list(), class = c("collector_character",
"collector")), MALES = structure(list(), class = c("collector_double",
"collector")), FEMALES = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), delim = ","), class = "col_spec"), class = c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"))
# Draw a pyramid plot
pop_df = pop %>%
dplyr::select(age_group,males,females) %>%
gather(key = Type, value = Value, -c(age_group))
# Make male values negative
pop_df$Value <- ifelse(pop_df$Type == "males", -1*pop_df$Value, pop_df$Value)
ggplot(pop_df, aes(x = age_group, y = Value, fill = Type)) +
geom_bar(data = subset(pop_df, Type == "females"), stat = "identity") +
geom_bar(data = subset(pop_df, Type == "males"), stat = "identity") +
scale_y_continuous(labels = abs) +
labs(x = "Age group", y = "Value", fill = "Gender") +
coord_flip()
由代表 package (v2.0.1) 於 2022 年 7 月 27 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.