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

图片拼接

<pre>library(gridExtra)
grid.arrange(p1,p2,p3,p4,ncol=2,nrow=2)   # 图例没有拼接
</pre>
image.png
<pre>###方法2 
library(patchwork)
p1+p2+p3+p4   ### 图例没有拼接
</pre>
image.png
<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

参考:qplot()函数的详细用法 - 子非鱼smile - 博客园 (cnblogs.com)

15.R语言绘图 | ggplot2_图例共享合并_哔哩哔哩_bilibili

上一篇 下一篇

猜你喜欢

热点阅读