Home > other >  bin size in pyramid_chart in R
bin size in pyramid_chart in R

Time:06-01

I'm currently trying to understand why the bin size in my pyramid chart in R (running in JupyterNotebook) is off.

I have a very simple table from where I use 3 variables: gender, age group, and count.

See table below:

enter image description here

And ran a pyramid_chart, however, the size of bars is off ,and I do not know how to fix it.

enter image description here

I tried to have a pyramid chart (also called as a bidirectional chart or a side to side chart), but I have issues with the facet_share that is giving me an error: R[write to console]: Error in axes$y$left[[1]]$children$axis$grobs[[lab_idx]] : attempt to select less than one element in get1index.

The code I used looked as following:

enter image description here

Data 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"))

CodePudding user response:

The size of the bars differ because the groups are uneven. Group 55-64 is only present in Female. If you add a row with add_row filling in the counterpart of age_group 55-64 for Male , then the bars will be as expected:

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
)

enter image description here

data:

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))
  • Related