繁体   English   中英

从 ggplot 中删除文本周围的所有白色边距

[英]Remove all white margins around text from ggplot

问题

我想创建一个 plot,它只包含文本并且文本周围的空白尽可能少。 我尝试使用annotate()但仍然有很多多余的空白。 尝试通过coord_cartesian()调整轴限制不起作用,因为文本只是停留在原处并调整到新的限制(参见 reprex)。

最终目标是只有一个文本框,然后我可以使用布局区域使用patchwork与图像对齐,以便文本和图像形成的线条对齐。 基本上,我想对标志和文本做与我上次TidyTuesday 贡献中相同的事情,而不必一点一点地移动文本和图像,以便它最终适合或更确切地说是“足够接近”。

代表

library(ggplot2)
library(ggtext)
text <- paste("iris data set gives the measurements in cm",
             "of the variables sepal length and width",
             "and petal length and width, respectively,",
             "for 50 flowers from each of 3 species of iris.",
             "The species are Iris setosa, versicolor, and virginica.", sep = "\n")

ggplot() + 
  annotate(
    'text',
    x = 0,
    y = 1,
    label = text,
    hjust = 0,
    vjust = 1
  ) +
  coord_cartesian(xlim = c(0, 0.5), ylim = c(0, 1)) +
  theme(plot.margin = margin()) +
  theme_void()

ggplot() + 
  annotate(
    'text',
    x = 0,
    y = 1,
    label = text,
    hjust = 0,
    vjust = 1
  ) +
  coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) + ## changed axis limits here
  theme(plot.margin = margin()) +
  theme_void()

reprex package (v2.0.0) 创建于 2022-03-10

编辑:按照建议尝试了 ggfittext 但不起作用

library(ggplot2)
library(ggtext)
text <- paste('iris data set gives the measurements in cm',
             "of the variables sepal length and width",
             "and petal length and width, respectively,",
             "for 50 flowers from each of 3 species of iris.",
             'The species are Iris setosa, versicolor, and virginica.', sep = "\n")


library(ggfittext)
ggplot() +
  geom_fit_text(
    aes(label = text, x = 1, y = 1),
    hjust = 0, grow = T,
    padding.x = grid::unit(0, "mm"),
    padding.y = grid::unit(0, "mm")
  ) +
  coord_cartesian(xlim = c(0.55, 1.45), ylim = c(0.5, 1.5), expand = F) +
  theme(plot.margin = margin())


ggplot() +
  geom_fit_text(
    aes(label = text, x = 1, y = 1),
    hjust = 0, grow = T,
    padding.x = grid::unit(0, "mm"),
    padding.y = grid::unit(0, "mm")
  ) +
  # Adjusted the y-limits here
  coord_cartesian(xlim = c(0.55, 1.45), ylim = c(0.75, 1.25), expand = F) +
  theme(plot.margin = margin())

reprex package (v2.0.0) 创建于 2022-03-10

ggfittext package 对我来说是新的,但似乎做得很好:

library(ggfittext)
ggplot() +
  geom_fit_text(
    aes(label = text, x = 1, y = 1),
    grow = TRUE, hjust = 0,
    padding.x = grid::unit(0, "mm"),
    padding.y = grid::unit(0, "mm")
  ) +
  theme_void() +
  theme(plot.margin = margin())

在此处输入图像描述

您仍然需要将图形 window 的大小调整为您想要的纵横比,但至少文本将根据 window 大小的限制尺寸进行缩放。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM