查看原文
其他

R可视化12|ggplot2-图层图形语法 (4)

pythonic生物人 pythonic生物人 2022-10-25

"pythonic生物人"的第110篇分享

本文系统介绍ggplot2的坐标系(coord)、分面(facet)。

本文目录

9、坐标系(coord)
  线性坐标系
  非线性坐标系

10、分面(facet)
  Facet wrap 
  Facet grid 

9、坐标系(coord

  • 线性坐标系

base <- ggplot(mpg, aes(displ, hwy)) + 
  geom_point() + 
  geom_smooth()
p1 <- base
p2 <- base + coord_cartesian(xlim = c(57))#设置坐标轴显示范围,突出显示图中某一部分



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

本文结束,更多好文:

有用请“点赞”“在看”“分享”

有意见请移步到QQ群629562529反馈,一起进步哈!

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存