在 R 中使用 ggplot2 的背靠背条形图

时间:2021-06-18 11:03:24

标签: r ggplot2 dplyr position

我正在尝试获得类似于此处显示的背靠背条形图(或金字塔图): Population pyramid with gender and comparing across two time periods with ggplot2 基本上,一个定量变量的金字塔图,其值必须显示为三个分类变量的组合。

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

1 个答案:

答案 0 :(得分:0)

在您下面的示例中,如果 df$Value,则 Gender == 'F' 为负数。您需要做类似的事情才能实现“绕轴对称躲避条”。