2017-12-27 12 views
2

Rで塗りつぶし矩形を作成し、その中央に白いテキストを配置してpngに書き出したいとします。私はrect()関数がおそらくこれを行うことができると知っていますが、私が四角形を見たすべての例がプロットに印刷されています。プロットなしでこれを行う方法はありますか?テキストで塗りつぶされた矩形を作成する

私はblogdown()サイトを構築し、Hugridテーマのものとほぼ同じように見える四角形を作成しようとしています。

答えて

1

まさに争点が何であるか、あなたの質問からかなり明確ではありません。 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) 

enter image description here

私は、この例では4つの長方形をしました。 1つだけ必要な場合は、1行だけの入力データフレームを作成することができます。

3

geom_rect()を使用して長方形を作成し、geom_text()を使用してテキストを貼り付けることができます。 ggplot2の矩形の見た目(色、線のサイズ、種類)を変更するのは簡単です。デフォルトのggplot2を削除するには、theme_classsic()element_blank()で見てください。

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

enter image description here

+1

は、このような場合のために、 'theme_voidは()'ありますです。テーマを手動で空にする必要はありません。 –

+0

@ClausWilkeありがとう!心に留めておきます – PoGibas

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) 

enter image description here

関連する問題