【发布时间】:2021-10-03 11:31:15
【问题描述】:
我在 R 中使用ggplot2 创建了以下图表。当我使用等于 -1 的 vjust 参数时,我使用 geom_text 生成的一些标签被截断(例如,第一和第二方面中的七月标签)。如果我对所有标签使用等于 +1 的 vjust 参数,也会发生同样的事情。有没有办法优化标签的位置,而不必在向量中手动指定每个vjust?
我希望避免在向量中手动指定每个 vjust 的原因是因为我希望图表尽可能灵活地适应值的任何变化。
library(tidyverse)
data <- structure(list(Date = structure(c(18779, 18809, 18840, 18871,
18901, 18932, 18779, 18809, 18840, 18871, 18901, 18932, 18779,
18809, 18840, 18871, 18901, 18932), class = "Date"), Key = c("Category 1",
"Category 1", "Category 1", "Category 1", "Category 1", "Category 1",
"Category 2", "Category 2", "Category 2", "Category 2", "Category 2",
"Category 2", "Category 3", "Category 3", "Category 3", "Category 3",
"Category 3", "Category 3"), Value = c(2.8, 3, 2, 2.7, 2.7, 2.8,
1, 2, -1.2, 0.3, 0.6, 0.8, 4, 3.7, 4.4, 4.4, 4.2, 4.2)), row.names = c(NA,
-18L), class = c("tbl_df", "tbl", "data.frame"))
ggplot(data, aes(Date, Value, col = Key)) +
geom_line(size = 2) +
facet_wrap(~Key, scales = 'free_y', nrow = 3) +
guides(col='none', linetype='none') +
geom_text(aes(label = paste0(sprintf('%0.1f', round(Value, digits = 2)), '%')), size = 5,
vjust = -1)
【问题讨论】: