R 中带有 ggplot2 的背靠背条形图

Back-to-back bar plot with ggplot2 in R

我正在尝试获得类似于此处所示的背靠背条形图(或金字塔图): 基本上,一个定量变量的金字塔图,其值必须显示为三个分类变量的组合。

library(ggplot2)
library(dplyr)
df <- data.frame(Gender = rep(c("M", "F"), each = 20),
                 Age = rep(c("0-10", "11-20", "21-30", "31-40", "41-50",
                             "51-60", "61-70", "71-80", "81-90", "91-100"), 4),
                 Year = factor(rep(c(2009, 2010, 2009, 2010), each=  10)),
                 Value = sample(seq(50, 100, 5), 40, replace = TRUE)) %>%
  mutate(Value = ifelse(Gender == "F", Value *-1 , Value))


ggplot(df) +
  geom_col(aes(fill = interaction(Gender, Year, sep = "-"),
               y = Value,
               x = Age),
           position = "dodge") +
  scale_y_continuous(labels = abs,
                     expand = c(0, 0)) +
  scale_fill_manual(values = hcl(h = c(15,195,15,195),
                                 c = 100,
                                 l = 65,
                                 alpha=c(0.4,0.4,1,1)),
                    name = "") +
  coord_flip() +
  facet_wrap(.~ Gender,
             scale = "free_x",
             strip.position = "bottom") +
  theme_minimal() +
  theme(legend.position = "bottom",
        panel.spacing.x = unit(0, "pt"),
        strip.background = element_rect(colour = "black"))

example of back-to-back barplot I want to mimick

试图在我的数据上模仿这个例子,从第一次调用 ggplot 函数开始就出错了,因为轴的两侧都没有躲避条形图:

mydf = read.table("https://raw.githubusercontent.com/gilles-guillot/IPUMS_R/main/tmp/df.csv",
                header=TRUE,sep=";")

ggplot(mydf) + 
  geom_col(aes(fill =  interaction(mig,ISCO08WHO_yrstud, sep = "-"),
               x = country,
               y = f), 
           position = "dodge") 

failed attempt to get a back-to-back bar plot

如我所料:

ggplot(df) +
  geom_col(aes(fill = interaction(Gender, Year, sep = "-"),
               y = Value,
               x = Age),
           position = "dodge")

geol_col plot with bar dodged symmetrically around axis

在您所关注的示例中,如果 Gender == 'F',则 df$Value 变为负数。你需要做类似的事情来实现“绕轴对称闪避”。