创建一个填充文本的矩形

Create a rectangle filled with text

我想在 R 中创建一个填充矩形,白色文本居中,并将其导出为 png。我知道 rect() 函数可能可以做到这一点,但我看到矩形的每个示例都打印在绘图上。有没有办法不用情节就可以做到这一点?

作为参考,我正在构建一个 blogdown() 网站并尝试创建一个看起来与 Hugrid 主题中的那些几乎相同的正方形。

您可以使用 geom_rect() 创建矩形并使用 geom_text() 将文本粘贴到其中。在 ggplot2 中修改矩形外观(颜色、线条大小或类型)很容易。您所要做的就是用 theme_classsic()element_blank().

删除默认的 ggplot2 外观
# Generate dummy dataset
foo <- data.frame(x1 = 1, x2 = 2, y1 = 1, y2 = 2,
                  text = paste(letters[1:3], letters[1:3], collapse = "\n"))

# Plot rectangle with text
library(ggplot2)
ggplot(foo) +
    geom_rect(aes(xmin = x1, xmax = x2, ymin = y1, ymax = y2),
              color = "black", size = 2, fill = "lightblue") +
    geom_text(aes(x = x1 + (x2 - x1) / 2, y = y1 + (y2 - y1) / 2,
                  label = text),
              size = 20) +
    theme_classic() +
    theme(axis.line  = element_blank(),
          axis.ticks = element_blank(),
          axis.text  = element_blank(),
          axis.title = element_blank())

从你的问题中还不太清楚症结所在。您是否需要从 R 生成矩形(而不是在 Illustrator 中手动生成)?而且不需要显示情节 window?

这一切都可以实现。我更喜欢用 ggplot2 绘图,这里你需要的特定几何图形是矩形的 geom_tile() 和文本的 geom_text()。您可以使用 ggsave().

保存为 png 而无需生成绘图
rects <- data.frame(x = 1:4,
                    colors = c("red", "green", "blue", "magenta"),
                    text = paste("text", 1:4))

library(ggplot2)
p <- ggplot(rects, aes(x, y = 0, fill = colors, label = text)) +
  geom_tile(width = .9, height = .9) + # make square tiles
  geom_text(color = "white") + # add white text in the middle
  scale_fill_identity(guide = "none") + # color the tiles with the colors in the data frame
  coord_fixed() + # make sure tiles are square
  theme_void() # remove any axis markings

ggsave("test.png", p, width = 4.5, height = 1.5)

我在这个例子中做了四个矩形。如果你只需要一个,你可以只制作一个只有一行的输入数据框。

这是一个轻量级的解决方案,

rects <- data.frame(fill = RColorBrewer::brewer.pal(5, "Pastel1"),
                    colour = RColorBrewer::brewer.pal(5, "Set1"),
                    label = paste("text", 1:5), stringsAsFactors = FALSE)
library(gridExtra)
gl <- mapply(function(f,l,c) grobTree(rectGrob(gp=gpar(fill=f, col="white",lwd=2)),
                                      textGrob(l, gp=gpar(col=c))),
             f = rects$fill, l = rects$label, c = rects$colour,
             SIMPLIFY = FALSE)

grid.arrange(grobs=gl)