我想使用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的纵横比”?
发布于 2019-04-25 11:06:34
一种选择是从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)
https://stackoverflow.com/questions/55840017
复制相似问题