[轉] R 繪圖ggplot2 一頁多圖及子圖嵌入主圖的多種實現方法
阿新 • • 發佈:2019-01-27
一、一面多圖的實現方法:
- 輸入:
minute <- c(110,118,120,123,131,137,144,149,152,160) VC <- c(5283,5299,5358,5292,5602,6014,5830,6102,6075,6411) lrdata <- data.frame(minute,VC) modelle <- lm(VC~minute,data=lrdata) pre <- predict(modelle,newdata=data.frame(minute),interval = "prediction") newlr <- cbind(lrdata,pre) p1<-ggplot(newlr,aes(x=minute,y=VC))+geom_point(size=3,colour="blue") p2<-ggplot(newlr,aes(x=minute,y=VC))+geom_point(size=3,colour="blue")+ geom_segment(aes(x=minute, xend=minute, y=VC, yend=fit),size=1,linetype=2,colour="red")+ geom_line(aes(y=fit), color = "blue", linetype = "dashed",size=1)
方法1:
- 輸入:
library(gridExtra)
grid.arrange(p1,p2,nrow=1)
- 結果:
方法2:
- 輸入:
library(Rmisc)
multiplot(p1,p2,cols=2)
- 結果:
方法3:
- 輸入:
install.packages("cowplot")
library(cowplot)
plot_grid(p1, NULL, NULL,p2, labels = c("A", "", "", "B"),ncol = 2)
- 結果:
二、子圖嵌入主圖的實現方法:
方法1:
- 輸入:
library(grid)
vp <- viewport(width = 0.3, height = 0.4, x = 0.65,y = 0.9,just=c("left","top"))
# width\height表示插入圖形的大小,x\y表示插入圖形相對於圖片底層just的位置
print(p1)
print(p2,vp=vp)
- 結果:
方法2:
- 輸入:
install.packages("viridis")
library(viridis)
ggdraw() +draw_plot(p1,0,0,1,1)+
draw_plot(p2,0.1,0.5,0.3,0.4)
# 0.1\0.5為圖的左下角x\y的位置,0.3\0.4為圖形的寬度和高度
- 結果: