【发布时间】: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