之前寫的博客中有提及過如何在 R 語言中繪制矢量圖,然后用于論文引用。但沒有專門開一篇博客來進行說明比較,這里重新開一篇博客來進行說明。
通常保存為矢量圖可能大多數時候是為了論文中的引用,所以格式一般為 EPS
, PDF
這兩種格式,這里也主要針對這兩種格式進行說明。
1. R 中自帶的默認繪圖
通常我們使用 plot(), lines(), points(), hist()
等一些 R 中自帶的繪圖工具,如果我們想要將圖片儲存為矢量圖的 PDF 格式應該怎么做呢?
1) PDF 格式
1
2
3
4
5
6
7
|
pdf( "example1.pdf" , width = 4 . 0 , height = 3 . 0 ) plot(rnorm( 100 ), main= "Hey Some Data" ) # 自己的繪圖函數 # ... # ... dev.off() |
非常簡單,只需用到 pdf()
函數即可。
2) EPS 格式
1
2
3
4
5
6
7
8
|
setEPS() postscript( "example1.eps" , width = 4 . 0 , height = 3 . 0 ) plot(rnorm( 100 ), main= "Hey Some Data" ) # 自己的繪圖函數 # ... # ... dev.off() |
eps 格式相對復雜,需用到 setEPS()
與 postscript()
函數。
2. ggplot 繪圖
利用 ggplot 繪制矢量圖就相對更加簡單了,每種方式都只需在最后加上一行代碼即可。
假設我們先利用 ggplot 進行繪圖(用例子中的圖):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
library(ggplot2) # Generate some sample data, then compute mean and standard deviation # in each group df <- data.frame( gp = factor(rep(letters[ 1 : 3 ], each = 10 )), y = rnorm( 30 ) ) ds <- plyr: :ddply (df, "gp" , plyr: :summarise , mean = mean(y), sd = sd(y)) # The summary data frame ds is used to plot larger red points on top # of the raw data. Note that we don't need to supply `data` or `mapping` # in each layer because the defaults from ggplot() are used. ggplot(df, aes(gp, y)) + geom_point() + geom_point(data = ds, aes(y = mean), colour = 'red' , size = 3 ) |
1) PDF 格式
這時我們要儲存為 PDF 格式的圖,只需在上述繪圖語句后面運行下述語句即可:
1
|
ggsave( "example2.pdf" , width = 4 . 0 , height = 3 . 0 ) |
2) EPS 格式
而 EPS 格式需要多一個參數: device = cairo_ps
1
|
ggsave( "example2.eps" , width = 4 . 0 , height = 3 . 0 , device = cairo_ps) |
以上就是R語言存儲矢量圖實現方式的詳細內容,更多關于R語言存儲矢量圖的資料請關注服務器之家其它相關文章!
原文鏈接:https://kanny.blog.csdn.net/article/details/100152389