【问题标题】:BarGraph with Primary and Secondary axis in rr 中具有主轴和辅助轴的条形图
【发布时间】:2020-02-10 10:14:33
【问题描述】:

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

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 绘制组合

【问题讨论】:

标签: r ggplot2 dplyr


【解决方案1】:

方法一

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

【讨论】:

  • 这有帮助,但我的挑战是 y 轴,即(AvgTopline 和 NrCustomers)不在同一比例上,从而影响图表的外观。此外,我的组合值由长度至少为 15 个字符的字符串组成。
  • 要处理不同的比例,在facet_grid 中设置scales = "free_y"。见?ggplot2::facet_grid。要处理较大的文本长度,您可以以一定角度打印 x 轴文本。请参阅编辑以进行澄清。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多