ggplot2 绘图:在导出为 PNG 图像时,如果超出绘图窗口,如何更改文本?

4
我想创建一个ggplot2图,手动指定y-lab和注释文本。如果y-lab/注释文本太长,我希望用较短的文本替换它。由于我需要对大量的图进行操作,所以需要自动完成此操作。
考虑以下示例数据和文本:
# 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()

enter image description here

此时,我想检查y轴标签是否被截断。如果文本被截断,我希望将其替换为以下内容:
# 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()

enter image description here

当我在绘图窗口中注释文本时,同样的问题会发生:

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

enter image description here

与之前相同的程序。如果文本被截断,我想将文本替换为以下内容:

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

enter image description here

如果这些文本太长,我该如何自动替换它们?

1
很遗憾,我不知道任何自动解决方案。通常我会进行导出->检查->修复大小或长度->导出->...直到我满意为止。如果有任何自动化的方法存在,我也非常感兴趣看看它是什么。 - Chelmy88
也许您可以检查绘图元素,大致确定字符串需要超出绘图尺寸的字符数(使用str_length(ggp1a$labs$y))。然后,您可以构建一个带有if else语句的函数来实现。虽然这种方法可能只适用于y标签。 - Ben G
2
在Ben的建议之后,您可能希望切换到等宽字体,这样您就可以确定有多少个字符适合。 - iod
1个回答

1
我不知道如何解决图表中的文字问题,除非它每次都在同一位置,但是这个方法可以解决你的ylab问题。
你可以创建一个类似这样的函数:
library(tidyverse)

long_short_ylab <- function(short, long) {
 if(str_length(long) > 50) { # adjust this number to whatever you figure out is your max length
   labs(y = short)
 } else {
   labs(y = long)
 }
}

你可以像这样在 ggplot 中使用它:
ggplot(data, aes(x = x, y = y)) +
  geom_point() + 
  long_short_ylab(short = text_short, long = text_long)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接