r - 如何修复 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.pdf
及plot3.pdf
以上,六边形的纵横比为 1:1,但绘图看起来不太好,因为coord_fixed
缩放了整个绘图区域,而不仅仅是六边形。
在每个情节中,我都可以调整bins
参数以获得纵横比接近 1:1 的六边形,但我希望自动为我挑选代码。有没有办法说“在 x 轴上选择 15 个箱,但是在 y 轴上需要很多箱才能使六边形具有 1:1 的纵横比”?
解决方案
一种选择是从 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)
推荐阅读
- r - 如何在 R Markdown 中将图像插入表格
- ruby-on-rails - 如何使用 pdf-forms gem 用图像填充 PDF?
- html - 将 .pug 编译为 html 后加载外部 CSS
- angular - 动态添加类等于字段/属性的值
- c - C Socket sendto 参数无效错误
- php - jason_decode JSON 到 PHP
- sql - 收到错误“关键字'as'附近的语法不正确”
- django - Django rest-framework 创建一个没有模型的视图
- javascript - 如何对 Mongo/Node 中的所有文档进行数值统计并生成一个值
- amazon-web-services - AWS SDK - 如何使用 Boto3 设置 VPC 名称标签