首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Gggplot2的geom_hex中调整宽高比?

如何在Gggplot2的geom_hex中调整宽高比?
EN

Stack Overflow用户
提问于 2019-04-25 07:54:44
回答 1查看 207关注 0票数 1

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

我见过coord_fixed (和它的别名coord_equal),但它们改变了整个绘图区域的纵横比,而我感兴趣的是改变六边形本身的纵横比。

代码语言:javascript
运行
复制
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的纵横比”?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-25 11:06:34

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

代码语言:javascript
运行
复制
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)

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

代码语言:javascript
运行
复制
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)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55840017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档