首页 > 解决方案 > r 中具有主轴和辅助轴的条形图

问题描述

我有一个数据框,我想创建一个带有主轴和次轴的条形图。

geom_bar(data=top_ten_S, aes(x=Combination, y=AvgTopline), stat="identity",fill="red") +
  coord_flip() +
  geom_text(
    data=top_ten_S,
    aes(
      x=Combination, y=AvgTopline,
      label=paste0("R",round(AvgTopline,0)),
      hjust=ifelse(AvgTopline < max(top_ten_S$AvgTopline) / 1.5, -0.1, 1.1), # <- Here lies the magic
    ),
  ) 

我的df看起来像

top_ten_S <- data.frame(Combination = c("a", "b", "c"),
                    Nrcustomers = c(20, 200, 1900),
                    AvgTopline = c(1000,3000,1500))

我只能用上面的代码绘制一列 - 我想要一个辅助轴,这样我就可以针对 NrCustomers 和 AvgTopline 绘制组合

标签: rggplot2dplyr

解决方案


方法一

top_ten_S %>% 
  gather(key, value, -Combination) %>% 
  ggplot(aes(x = Combination, y = value, fill = key)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(fill = "")

方法二

top_ten_S %>% 
  gather(key, value, -Combination) %>% 
  ggplot(aes(x = Combination, y = value, fill = key)) +
  geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
  facet_grid(. ~ key)

编辑:方法2

top_ten_S %>% 
  gather(key, value, -Combination) %>% 
  ggplot(aes(x = Combination, y = value, fill = key)) +
  geom_bar(stat = "identity", position = "dodge", show.legend = FALSE) +
  facet_grid(. ~ key, space = "free_y", scales = "free_y") +
  theme(axis.text.x = element_text(angle = 60))

推荐阅读