【问题标题】:How to automatically choose a good ylim to read geom_labels in ggplot2 in R如何自动选择一个好的 ylim 来读取 R 中 ggplot2 中的 geom_labels
【发布时间】:2021-01-11 20:34:02
【问题描述】:

假设我使用diamonds 数据集编写以下代码:

library(tidyverse)

diamonds %>% 
    group_by(cut) %>% 
    summarize(total_value = sum(price, na.rm = TRUE)) %>% 
    arrange(total_value) %>% 
    mutate(cut = as_factor(cut)) %>% 
    mutate(across(where(is.numeric), ~round(., 1))) %>% 
    ggplot(aes(x = cut, y = total_value)) +
    geom_col(aes(fill = cut)) +
    theme(legend.position = "note") +
    coord_flip() +
    geom_label(aes(label = paste0("$", total_value)), size = 6) +
    labs(title = "Total Value of Diamonds by Cut", y = "USD", x = "") +
    theme(axis.text = element_text(size = rel(1)))

输出如下图:

如您所见,无法读取第一类(“理想”)的最后一位数字。

所以,我的问题是,我知道我可以简单地写一些类似coord_flip(ylim = c(0,80000000) 的东西,这样就可以解决问题;但是,我可以写什么来代替 ggplot2 自动知道它应该在 ylim 中提供多少空间,以便人们可以清楚地阅读 geom_label()s 而无需我手动执行此操作?

我正在尝试创建一个包含多个绘图的自动仪表板,例如这样,但我无法手动调整其中的每一个,我需要一个自动机制,我还没有在 StackOverflow 上为 geom_label() 找到任何与此相关的信息.

谢谢。

【问题讨论】:

  • + scale_y_continuous(expand = c(0.05, 0, 0.1, 0)) 可能会有所帮助。它设置的上部扩展是当前大小的两倍。根据需要增加0.1
  • 好吧,为每种条形添加标签会破坏拥有 x 轴的全部目的。如果您需要每个人都看到确切的金额,也许只显示一个表格而不是条形图。或者,如果您真的需要标签,请将所有标签放在左侧。他们真的有理由需要在酒吧的左边吗?

标签: r ggplot2 plot graph tidyverse


【解决方案1】:

您可以将label 移动到靠近中间的位置,然后用vjust 调整位置,这样它就不会溢出到包含条形的绘图集之外,而不是定位。

library(tidyverse)

diamonds %>% 
  group_by(cut) %>% 
  summarize(total_value = sum(price, na.rm = TRUE)) %>% 
  arrange(total_value) %>% 
  mutate(cut = as_factor(cut)) %>% 
  mutate(across(where(is.numeric), ~round(., 1))) %>% 
  ggplot(aes(x = cut, y = total_value)) +
  geom_col(aes(fill = cut)) +
  theme(legend.position = "note") +
  coord_flip() +
  geom_label(aes(label = paste0("$", total_value), y = total_value/2), size = 6, hjust = 0.2) +
  labs(title = "Total Value of Diamonds by Cut", y = "USD", x = "") +
  theme(axis.text = element_text(size = rel(1)))

这给了:

【讨论】:

  • 这是一个合理的解决方案。另外,感谢@teunbrand 提到+ scale_y_continuous(expand = c(0.05, 0, 0.1, 0)) 的使用,这也很有帮助。
猜你喜欢
  • 2022-07-23
  • 2015-05-21
  • 2017-11-01
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 2012-10-07
  • 2018-03-26
相关资源
最近更新 更多