r - ggExtra绘图格式:不同绘图尺寸的相似边际绘图

标签 r plot ggplot2

有关格式化使用ggplot2 + ggExtra生成的图的问题,与任何错误无关。

require(ggplot2)
#> Loading required package: ggplot2
require(ggExtra)
#> Loading required package: ggExtra
p1 <- ggplot(data = mpg,aes(x = cty,y = cty)) + 
  geom_point()+ 
  xlab("City driving (miles/gallon)") +
  ylab("City driving (miles/gallon)")

ggMarginal(p = p1,type= "boxplot")


此图表中的y轴边际图通常与x轴边际图不相似,即2个箱形图的宽度不相似。当更改绘图尺寸(在我的情况下,使用RStudio)时,此问题变得更加严重。在使用不同的绘图尺寸(宽度x高度)时,如何使2个箱形图的宽度相似的任何建议。

ggExtra软件包提供的其他边际图类型选项面临类似的问题:直方图,密度。

最佳答案

我建议使用cowplot软件包中的axis_canvas函数。 (免责声明:我是程序包的作者。)它需要做更多的工作,但是它允许您绘制所需的边际。您可以精确指定尺寸,以输出单位(例如英寸)为单位。

require(cowplot)

pmain <- ggplot(data = mpg, aes(x = cty, y = hwy)) + 
  geom_point() + 
  xlab("City driving (miles/gallon)") +
  ylab("Highway driving (miles/gallon)")

xbox <- axis_canvas(pmain, axis = "x", coord_flip = TRUE) + 
  geom_boxplot(data = mpg, aes(y = cty, x = 1)) + coord_flip()
ybox <- axis_canvas(pmain, axis = "y") + 
  geom_boxplot(data = mpg, aes(y = hwy, x = 1))

p1 <- insert_xaxis_grob(pmain, xbox, grid::unit(1, "in"), position = "top")
p2 <- insert_yaxis_grob(p1, ybox, grid::unit(1, "in"), position = "right")
ggdraw(p2)


在下面两个具有不同长宽比的图像中,查看框线图如何保持其宽度/高度。 (不幸的是,Stackoverflow会重新缩放图像,因此效果有些模糊,但是您可以看到顶部箱形图的高度始终等于侧面一角的宽度。)

enter image description here

enter image description here

第二个优点是,因为您可以将成熟的ggplot2用于边际图,所以您可以绘制任何想要的东西,例如分组箱图。

require(cowplot)

pmain <- ggplot(data = mpg, aes(x = cty, y = hwy, color = factor(cyl))) + 
  geom_point() + 
  xlab("City driving (miles/gallon)") +
  ylab("Highway driving (miles/gallon)") +
  theme_minimal()

xbox <- axis_canvas(pmain, axis = "x", coord_flip = TRUE) + 
  geom_boxplot(data = mpg, aes(y = cty, x = factor(cyl), color = factor(cyl))) + 
  scale_x_discrete() + coord_flip()
ybox <- axis_canvas(pmain, axis = "y") + 
  geom_boxplot(data = mpg, aes(y = hwy, x = factor(cyl), color = factor(cyl))) +
  scale_x_discrete()

p1 <- insert_xaxis_grob(pmain, xbox, grid::unit(1, "in"), position = "top")
p2 <- insert_yaxis_grob(p1, ybox, grid::unit(1, "in"), position = "right")
ggdraw(p2)


enter image description here

关于r - ggExtra绘图格式:不同绘图尺寸的相似边际绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47446458/

相关文章:

r - R Markdown 中带有 pdf_document 输出的表格和绘图之间的换行符

r - 在ggmap中绘制曲线,geom_curve不起作用

r - 确定 R 中的下一行

iphone - OBJ-C : Getting the minimum/maximum value in a NSMutableArray

r - 如何在ggplot2中扩展调色板

用于文本 3D 散点图的 Java 库

r - 每组使用 2 种颜色进行绘图

python - 绘图 : single big column and its frequencies

r - 使用 nlme 和 lsoda 拟合一阶方程

r - 无法获得 flexdashboard modal Shiny react 性来处理 NULL 状态