【问题标题】:ggplot2 Plot: Change Text in Case it Exceeds the Plot Window when Exporting as PNGggplot2 绘图:在导出为 PNG 时更改文本以防超出绘图窗口
【发布时间】: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 的建议,您可能想要切换到单型字体,这样您就可以确定可以容纳多少个字符。

标签: r ggplot2 plot text


【解决方案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)

【讨论】:

    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多