R可视化12|ggplot2-图层图形语法 (4)
程序员文章站
2022-03-07 21:40:50
本文系统介绍ggplot2的坐标系(coord)、分面(facet)。...
本文系统介绍ggplot2的坐标系(coord)、分面(facet)。
本文目录
9、坐标系(coord)
-
线性坐标系
base <- ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth()
p1 <- base
p2 <- base + coord_cartesian(xlim = c(5, 7))#设置坐标轴显示范围,突出显示图中某一部分
p3 <- ggplot(mpg, aes(cty, displ)) +
geom_point() +
geom_smooth()
p4 <- ggplot(mpg, aes(displ, cty)) +
geom_point() +
geom_smooth() +
coord_flip()#最大程度拟合
p5 <- ggplot(mpg, aes(displ, cty)) +
geom_point() +
geom_smooth() +
coord_fixed()#x y轴切换
p6 <- grid.arrange(p1,p2,p3,p4,p3,p5,nrow = 3)
ggsave("scale26.png", p6, width = 6.5, height = 5)
-
非线性坐标系
10、分面(facet)
Facets divide a plot into subplots based on the values of one or more discrete variables, 分三类。
-
facet_null()
: a single plot, the default. -
facet_wrap()
: “wraps” a 1d ribbon of panels into 2d. -
facet_grid()
: produces a 2d grid of panels defined by variables which form the rows and columns.
-
Facet wrap
options(repr.plot.width = 4.5, repr.plot.height = 5, repr.plot.res = 300)
mpg2 <- subset(mpg, cyl != 5 & drv %in% c("4", "f") & class != "2seater")
base <- ggplot(mpg2, aes(displ, hwy)) +
geom_blank() +
xlab(NULL) +
ylab(NULL)
p1 <- base + facet_wrap(~class, ncol = 3)#三列展示
p2 <-base + facet_wrap(~class, ncol = 3, as.table = FALSE)
p3 <- base + facet_wrap(~class, nrow = 3)#三行展示
p4 <- base + facet_wrap(~class, nrow = 3, dir = "v")#
p5 <- grid.arrange(p1,p2,p3,p4,nrow = 2)
ggsave("scale28.png", p5, width = 6.5, height = 5)
-
Facet grid
#效果见图
options(repr.plot.width = 4.5, repr.plot.height = 5, repr.plot.res = 300)
p1 <- base
p2 <- base + facet_grid(. ~ cyl)#通过cyl按列绘图
p3 <- base + facet_grid(drv ~ .)#通过drv按行绘图
p4 <- base + facet_grid(drv ~ cyl)#通过drv按行绘图,通过cyl按列绘图
p5 <- grid.arrange(p1,p2,p3,p4,nrow = 2)
ggsave("scale29.png", p5, width = 6.5, height = 5)
本文结束,更多好文,欢迎关注:pythonic生物人
本文地址:https://blog.csdn.net/qq_21478261/article/details/109086722
推荐阅读