R 中 pyramid_chart 中的 bin 大小

bin size in pyramid_chart in R

我目前正在尝试了解为什么我的 R 金字塔图表(JupyterNotebook 中的 运行)中的 bin 大小关闭。

我有一个非常简单的 table,其中我使用了 3 个变量:genderage groupcount

见下文table:

和运行一个pyramid_chart,但是,条的大小不对,我不知道如何解决。

我尝试制作金字塔图(也称为 bidirectional chartside to side chart),但我遇到了 facet_share 的问题,它给我一个错误:R[write to console]: Error in axes$y$left[[1]]$children$axis$grobs[[lab_idx]] : attempt to select less than one element in get1index.

我使用的代码如下所示:

数据table

val_gen_age<-data.frame(gender = c("Female", "Female","Female","Female","Female","Female","Male","Male","Male","Male","Male"), age group  = c("18-24", "25-34", "35-44","45-54","55-64","65+","18-24", "25-34", "35-44","45-54","55-64"),count = c("1270", "2280", "1257","855","180","450","1449","1170","89"))

条形的大小不同,因为组不均匀。第 55-64 组仅出现在 Female 中。如果您添加一行 add_row 填充 Maleage_group 55-64 的对应行,则条形图将如预期的那样:

library(dplyr)
library(ggcharts)

df1 <- df %>% 
   add_row(gender ="Male", age_group = "55-64", count = 0)
 
pyramid_chart(
  df1,
  age_group,
  count,
  gender,
  bar_colors =  c("darkgreen", "darkorange"),
  sort = "no",
  xlab = NULL,
  title = NULL
)

数据:

structure(list(gender = c("Female", "Female", "Female", "Female", 
"Female", "Male", "Male", "Male", "Male"), age_group = c("18-24", 
"25-34", "35-44", "45-54", "55-64", "18-24", "25-34", "35-44", 
"45-54"), count = c(1270L, 2280L, 1257L, 855L, 180L, 450L, 1449L, 
1170L, 89L)), class = "data.frame", row.names = c(NA, -9L))