1. 安装ggpattern包
1 2 3 4 5 6
| options(repos =structure(c(CRAN ="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")))
install.packages("remotes") remotes::install_github("coolbutuseless/ggpattern")
|
如果remotes方式安装失败,可以从github直接下载zip文件,使用yulabs的install_zip安装,但是要先安装依赖包
1 2 3 4
| install.packages(c("gridGeometry", "sf", "png")) library(yulab.utils) install_zip(file ="E:/下载/ggpattern-master.zip")
|
2. 绘图
其他的图略过,本次仅想要通过R来绘制prism graphpad的填充图案的柱状图。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| library(ggplot2) library(ggpattern) library(ggprism)
df <-data.frame( trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2) )
ggplot(df, aes(trt, outcome)) + geom_col_pattern( aes(pattern_type = trt), pattern = 'magick', pattern_scale = 3, pattern_fill = "black", fill = "white", colour = 'black', size = 1, pattern_density = 0.1) + scale_y_continuous(limits = c(0, 3.5),expand = c(0,0)) + theme_prism() + labs(title = "col") + scale_pattern_type_discrete(choices = c('gray100', 'hs_bdiagonal','vertical'))
|
绘图结果:
如果是批量的绘图,R肯定比prism来的方便和快捷。
图案填充有54中可供选择的图案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| ggpattern::magick_pattern_names [1] "bricks" "checkerboard" "circles" [4] "crosshatch" "crosshatch30" "crosshatch45" [7] "fishscales" "gray0" "gray5" [10] "gray10" "gray15" "gray20" [13] "gray25" "gray30" "gray35" [16] "gray40" "gray45" "gray50" [19] "gray55" "gray60" "gray65" [22] "gray70" "gray75" "gray80" [25] "gray85" "gray90" "gray95" [28] "gray100" "hexagons" "horizontal" [31] "horizontal2" "horizontal3" "horizontalsaw" [34] "hs_bdiagonal" "hs_cross" "hs_diagcross" [37] "hs_fdiagonal" "hs_horizontal" "hs_vertical" [40] "left30" "left45" "leftshingle" [43] "octagons" "right30" "right45" [46] "rightshingle" "smallfishscales" "vertical" [49] "vertical2" "vertical3" "verticalbricks" [52] "verticalleftshingle" "verticalrightshingle" "verticalsaw"
|
其中有一些跟Prism graphpad是可以做到一样的,但是斜线这里是弯弯曲曲的,比如上图用的hs_bdiagonal。
但是,在浏览了最近看的文献以后,发现其实很少有文章使用这种斜线、点、图案填充的柱状图。大部分都是黑白、灰度或者彩色的图。而这种图根本不需要用到ggpattern。因此,该包的实际应用场景不多。
当然,除了图案填充之外,还有渐变填充、圆圈填充、自定义图案填充等,比如渐变填充:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| ggplot(mtcars) + geom_density_pattern( aes( x = mpg, pattern_fill =as.factor(cyl), pattern_orientation =as.factor(cyl) ), pattern ='gradient', pattern_fill2 =NA, fill =NA ) + theme_bw(15) + labs( title ="Pattern is 'gradient'" ) + theme(legend.key.size =unit(1.5, 'cm')) + coord_fixed(ratio =80)
|
输出结果: