如何在ggplot2的geom_hex中固定长宽比?

时间:2019-04-24 23:54:44

标签: r ggplot2

我想用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的长宽比”?

1 个答案:

答案 0 :(得分:2)

一种选择是从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)

enter image description here

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

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)

enter image description here