【问题标题】:Create a rectangle filled with text创建一个填充有文本的矩形
【发布时间】:2017-12-27 03:39:32
【问题描述】:

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

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

【问题讨论】:

    标签: r ggplot2 blogdown


    【解决方案1】:

    您可以使用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())
    

    【讨论】:

    • theme_void() 用于此类情况。无需手动清空主题。
    【解决方案2】:

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

    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)
    

    【讨论】:

      【解决方案3】:

      从您的问题中,您并不清楚症结究竟是什么。您是否需要从 R 生成矩形(而不是在 Illustrator 中手动生成)?并且不需要显示绘图窗口?

      这一切都可以实现。我更喜欢用 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)
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-13
        • 1970-01-01
        • 2011-03-20
        • 1970-01-01
        • 2018-08-25
        • 2020-07-07
        • 2016-02-24
        • 1970-01-01
        相关资源
        最近更新 更多