首页 > 解决方案 > 如何修复 ggplot2 的 geom_hex 中的纵横比?

问题描述

我想用它geom_hex来表示我的计数,但我希望六边形是“正方形的”,纵横比为 1:1。

我见过coord_fixed(及其别名coord_equal),但这些改变了整个绘图区域的纵横比,而我对改变六边形本身的纵横比感兴趣。

library(ggplot2)

# Here, in plot1.pdf, the hexagon aspect ratio is determined by 
# the saved plot aspect ratio
plt1 <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_hex(bins = 10)
ggsave("plot1.pdf", plt1, width = 5, height = 4)


# Here, in plot2.pdf, the hexagon aspect ratio is 1:1, but the
# plot doesn't fill the space well, particularly if the data change
ratio <- 2
plt2 <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_hex(bins = 10 * c(1, ratio)) +
  coord_fixed(ratio = ratio)
ggsave("plot2.pdf", plt2, width = 5, height = 4)


# In plot3.pdf, the only thing that's changed is the y-axis data,
# but the plot is unreadable because the x-axis is so compressed
ratio <- 2
plt3 <- ggplot(iris, aes(x = Sepal.Width, y = 5 * Sepal.Length)) +
  geom_hex(bins = 10 * c(1, ratio)) +
  coord_fixed(ratio = ratio)
ggsave("plot3.pdf", plt3, width = 5, height = 4)

plot2.pdfplot3.pdf以上,六边形的纵横比为 1:1,但绘图看起来不太好,因为coord_fixed缩放了整个绘图区域,而不仅仅是六边形。

在每个情节中,我都可以调整bins参数以获得纵横比接近 1:1 的六边形,但我希望自动为我挑选代码。有没有办法说“在 x 轴上选择 15 个箱,但是在 y 轴上需要很多箱才能使六边形具有 1:1 的纵横比”?

标签: rggplot2

解决方案


一种选择是从 ggplot 中提取绘图区域的大小(以轴为单位),然后根据比率缩放六边形(使用binwidth而不是bins参数)。

plt1 = ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_hex() 

xrange = diff(ggplot_build(plt1)$layout$panel_params[[1]]$x.range)
yrange = diff(ggplot_build(plt1)$layout$panel_params[[1]]$y.range)
ratio = xrange/yrange
xbins = 10
xwidth = xrange/xbins
ywidth = xwidth/ratio
plt1 = ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_hex(binwidth = c(xwidth,ywidth)) +
  coord_fixed(ratio = ratio)
ggsave("plot1.pdf", plt1, width = 5, height = 4)

在此处输入图像描述

或者,如果您希望绘图区域的纵横比与页面相同,而不是正方形,那么您可以相应地调整比率:

width = 5 
height = 4
ratio = (xrange/yrange) * (height/width)

xwidth = xrange/xbins
ywidth = xwidth/ratio
plt1 = ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_hex(binwidth = c(xwidth,ywidth)) +
  coord_fixed(ratio = ratio)

ggsave("plot1.pdf", plt1, width = width, height = height)

在此处输入图像描述


推荐阅读