ggExtra绘图格式:不同绘图尺寸的类似边缘图

时间:2017-11-23 01:57:58

标签: 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高度)使两个箱图的宽度相似。

我面临与ggExtra包提供的其他边缘绘图类型选项类似的问题:直方图,密度。

2 个答案:

答案 0 :(得分:2)

我建议使用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

答案 1 :(得分:0)

我不完全确定你的意思。设置宽度=输出图的高度可确保箱图的宽度相同。

例如,在RMarkdown中,如果我包含

```{r, fig.width = 5, fig.height = 5}
ggMarginal(p1, type = "boxplot", size = 2);
```

我得到以下输出

enter image description here

盒子宽度相同。

或者,如果保存图表,请确保设置相同的宽度和高度。

ggsave(file = "test.png", ggMarginal(p1, type = "boxplot", size = 2), width = 5, height = 5);