按照某个因子分面
library(tidyverse)
mtcars_tbl<-rownames_to_column(mtcars,var = 'car')%>%
mutate(cyl=factor(cyl),
am=if_else(am==1,'A','M'),
vs=if_else(vs==1,'V','L'))
ggplot(mtcars_tbl,aes(x=wt,y=mpg))+
geom_point(shape=21,
alpha=0.5,
aes(size=disp,fill=factor(cyl)))+
scale_fill_npg()+
scale_size(range = c(1,20))+
facet_grid(~am)+ #按照am分面
theme_bw()

image.png
ggplot(mtcars_tbl,aes(x=wt,y=mpg))+
geom_point(shape=21,
alpha=0.5,
aes(size=disp,fill=factor(cyl)))+
scale_fill_npg()+
scale_size(range = c(1,20))+
facet_grid(vs~am, scale='free')+ #前面是行,后面是列,坐标自动调整
theme_bw()

image.png
small_diamonds<-sample_n(diamonds,size=500)
ggplot(data=small_diamonds,aes(x=carat,y=price))+
geom_point(shape=21,size=2,color='black',aes(fill=cut))+
scale_fill_npg()+
facet_wrap(~color,ncol = 4)+ #facet_wrap可以自己调数目
theme_bw()+
theme(legend.position = c(0.9,0.25))

image.png
不同变量分面
library(ggforce)
ggplot(mtcars_tbl,aes(x=.panel_x,y=.panel_y))+
geom_point(shape=21,
alpha=0.5,
aes(fill=factor(cyl)))+
scale_fill_npg()+
facet_matrix(vars(disp,wt,mpg,qsec))+ #每个数据之间相互出图
theme_bw()

image.png
ggplot(mtcars_tbl,aes(x=.panel_x,y=.panel_y))+
geom_point(shape=21,
alpha=0.5,
aes(fill=factor(cyl)))+
scale_fill_npg()+
facet_matrix(rows=vars(disp,wt), cols=vars(mpg,qsec))+ #设定行和列
theme_bw()

image.png
facet_zoom局部放大
library(ggforce)
ggplot(iris,aes(x=Petal.Length,y=Petal.Width,color=Species))+
geom_point(size=2)+
scale_fill_npg()+
theme_test()+
facet_zoom(x=Species=="versicolor",zoom.size = 1) #Species=="versicolor"投射到X轴,把zoom.size=1 等比例放大

image.png
按照坐标放大
ggplot(iris,aes(x=Petal.Length,y=Petal.Width,color=Species))+
geom_point(size=2)+
scale_fill_npg()+
theme_test()+
facet_zoom(xlim=c(3.5,5.3),ylim=c(1.3,2),zoom.size = 1) #按照坐标放大

image.png
添加注释
ggplot(iris,aes(x=Petal.Length,y=Petal.Width,color=Species))+
geom_point(size=2)+
scale_fill_npg()+
theme_test()+
geom_mark_ellipse(aes(label=Species))+
theme(legend.position = 'none')

image.png
网友评论