【发布时间】:2019-08-23 11:56:45
【问题描述】:
我想使用手动指定的 y-lab 和图中的注释文本创建一个 ggplot2 图。如果 y-lab/annotated 文本太长,我想用更短的文本替换它。这需要自动完成,因为我需要为大量地块执行此操作。
考虑以下示例数据和文本:
# Create example data
set.seed(123)
data <- data.frame(x = rnorm(100),
y = rnorm(100))
# Create two text versions
text_long <- "This is a very long text which might exceed the plot limits"
text_short <- "Short text"
现在,我可以按如下方式创建和导出 ggplot:
# Load ggplot2 package
library("ggplot2")
# Create first plot
ggp1a <- ggplot(data, aes(x = x, y = y)) +
geom_point() +
ylab(text_long)
# Export first plot as png
png("C:/Your-Path/my_plot1a.png", res = 300, height = 500, width = 1500)
ggp1a
dev.off()
此时,我想检查一下 y-lab 文本是否被截断。如果文本被截断,我想将文本替换如下:
# Create second plot
ggp2a <- ggplot(data, aes(x = x, y = y)) +
geom_point() +
ylab(text_short) # Short text
# Export second plot as png
png("C:/Your-Path/my_plot2a.png", res = 300, height = 500, width = 1500)
ggp2a
dev.off()
当我在绘图窗口中注释文本时也会出现同样的问题:
# Create first plot
ggp1b <- ggplot(data, aes(x = x, y = y)) +
geom_point() +
annotate("text", x = 2, y = 2, col = 2, label = text_long)
# Export first plot as png
png("C:/Your-Path/my_plot1b.png", res = 300, height = 500, width = 1500)
ggp1b
dev.off()
和之前一样。如果文本被截断,我想将文本替换如下:
# Create second plot
ggp2b <- ggplot(data, aes(x = x, y = y)) +
geom_point() +
annotate("text", x = 2, y = 2, col = 2, label = text_short) # Short text
# Export second plot as png
png("C:/Your-Path/my_plot2b.png", res = 300, height = 500, width = 1500)
ggp2b
dev.off()
如果这些文本太长,我如何自动替换它们?
【问题讨论】:
-
不幸的是,我不知道有任何自动解决方案。通常我会导出 -> 检查 -> 修复大小或长度 -> 导出 -> ...直到我满意为止。如果存在任何自动方式,我也会非常有兴趣看到它
-
也许检查你的情节元素并粗略地找出字符串有多少字符会超出情节的尺寸(使用
str_length(ggp1a$labs$y))。然后,您可以使用 if else 语句构建一个函数来执行此操作。尽管此方法可能仅适用于您的 y 标签。 -
根据 Ben 的建议,您可能想要切换到单型字体,这样您就可以确定可以容纳多少个字符。