R语言——ggplot2图形拼接
2022-07-08 本文已影响0人
monkey_study
R语言——ggplot2图形拼接
————————————————————————
rm(list=ls())
options(stringsAsFactors = F)
#### 加载包
library(ggplot2)
?diamonds
# price price in US dollars (\$326–\$18,823)
#
# carat weight of the diamond (0.2–5.01)
#
# cut quality of the cut (Fair, Good, Very Good, Premium, Ideal)
#
# color diamond colour, from D (best) to J (worst)
#
# clarity # 钻石透明度
#
# x length in mm (0–10.74)
#
# y width in mm (0–58.9)
#
# z depth in mm (0–31.8)
# depth total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43–79)
# table width of top of diamond relative to widest point (43–95)
# qplot quick plot 快速绘图函数
# 测试数据集,ggplot2内置的钻石数据
qplot(carat, price, data = diamonds)
dsmall <- diamonds[sample(nrow(diamonds), 100), ] #对diamonds数据集进行抽样</pre>
绘图
<pre>p1=qplot(carat,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(nrow = 1,byrow = T))+ # 图例设置
theme(legend.position = 'top')</pre>
image.png
<pre>p2=qplot(cut,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(nrow = 1,byrow = T))+ # 图例设置
theme(legend.position = 'top')
p2</pre>
image.png
<pre>p3=qplot(color,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(nrow = 1,byrow = T))+ # 图例设置
theme(legend.position = 'top')
p3</pre>
image.png
<pre>p4=qplot(depth,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(nrow = 1,byrow = T))+ # 图例设置
theme(legend.position = 'top')
p4</pre>
image.png
图片拼接
- method 1
<pre>library(gridExtra)
grid.arrange(p1,p2,p3,p4,ncol=2,nrow=2) # 图例没有拼接
</pre>
image.png
- method 2
<pre>###方法2
library(patchwork)
p1+p2+p3+p4 ### 图例没有拼接
</pre>
image.png
- method 3 —— 图例共享
<pre>library(lemon)
grid_arrange_shared_legend(p1,p2,p3,p4,ncol=2,nrow = 2,position = 'top')
grid_arrange_shared_legend(p1,p2,p3,p4,ncol=2,nrow = 2,position = "bottom") #position 参数控制图例位置
</pre>
image.png
image.png
图例显示在右边
<pre>p1=qplot(carat,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(ncol = 1,bycol = T))+ # 图例设置
theme(legend.position = 'top')
p2=qplot(cut,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(ncol = 1,bycol = T))+ # 图例设置
theme(legend.position = 'right')
p3=qplot(color,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(ncol = 1,bycol = T))+ # 图例设置
theme(legend.position = 'top')
p4=qplot(depth,price,data = dsmall,colour=clarity)+ # 映射
guides(colour=guide_legend(ncol = 1,bycol = T))+ # 图例设置
theme(legend.position = 'top')
grid_arrange_shared_legend(p1,p2,p3,p4,ncol=2,nrow = 2,position = 'right')
</pre>
image.png