使用ggplot2,如何在使用coord_trans函数时根据未变换的坐标比例定位geom_tile?

问题描述 投票:0回答:1

最初的情节是:

rect <- data.frame(x = 100, y = 50)
line <- data.frame(x = c(1, 200), y = c(100, 1))

library(ggplot2)
plot1 <- ggplot(mapping = aes(x, y)) +
  scale_x_continuous(limits=c(1, 200), expand=c(0,0), breaks = c(1,50,100,150,200)) +
  scale_y_continuous(limits=c(1, 100), expand=c(0,0), breaks = c(1,25,50,75,100)) +
  theme(axis.title=element_text(colour="black",size=22)) +
  theme(axis.text=element_text(colour="black",size=20)) +
  theme(plot.margin=unit(c(0.3, 0.8, 0.1, 0.2),"cm")) +
  geom_tile(data = rect, aes(width = 100, height = 50), alpha = 0.4) + 
  geom_line(data = line) + 
  theme(panel.grid.major=element_line(colour="grey60"))
plot1

目标是

modulus_trans(0.3)
轴的缩放方式使得黑线遵循这些变换,但灰色框必须根据未变换坐标的比率保持定位(即从 x 和 y 的 25% 开始) ,然后覆盖宽度和高度的 50%)。

coord_trans
函数会适当地变换比例和线条,但不幸的是,还会变换框:

library(scales)
plot2 <- ggplot(mapping = aes(x, y)) + 
  scale_x_continuous(limits=c(1, 200), expand=c(0,0), breaks = c(1,50,100,150,200)) +
  scale_y_continuous(limits=c(1, 100), expand=c(0,0), breaks = c(1,25,50,75,100)) +
  theme(axis.title=element_text(colour="black",size=22)) +
  theme(axis.text=element_text(colour="black",size=20)) +
  theme(plot.margin=unit(c(0.3, 0.8, 0.1, 0.2),"cm")) +
  geom_tile(data = rect, aes(width = 100, height = 50), alpha = 0.4) + 
  geom_line(data = line) + 
  theme(panel.grid.major=element_line(colour="grey60")) +
  coord_trans(x = modulus_trans(0.3), y = modulus_trans(0.3))
plot2  

是否有一种简单的方法可以通过根据 x 和 y 的 % 定位框来生成以下所需的图,而不是手动?

感谢您的帮助

r ggplot2 scale coordinate-transformation
1个回答
0
投票

我想我只需创建一个小函数来计算具有给定比例的变换坐标的点将在哪里:

f <- function(x, max = 200, min = 1, trans = modulus_trans(0.3)) {
  min_trans <- trans$trans(min)
  max_trans <- trans$trans(max)
  trans$inv(min_trans + x * (max_trans - min_trans))
}

这允许我们使用

geom_rect
代替
geom_tile
:

plot2 <- ggplot(line, mapping = aes(x, y)) + 
  geom_line() + 
  geom_rect(aes(xmin = f(0.25, 200), xmax = f(0.75, 200),
                ymin = f(0.25, 100), ymax = f(0.7575, 100)), alpha = 0.4) +
  scale_x_continuous(limits = c(1, 200), breaks = c(1, 1:4 * 50)) +
  scale_y_continuous(limits = c(1, 100), breaks = c(1, 1:4 * 25)) +
  coord_trans(x = modulus_trans(0.3), y = modulus_trans(0.3), expand = FALSE) +
  theme(axis.title       = element_text(colour = "black", size = 22),
        axis.text        = element_text(colour = "black", size = 20),
        plot.margin      = unit(c(0.3, 0.8, 0.1, 0.2), "cm"), 
        panel.grid.major = element_line(colour = "grey60")) 

我们可以使用

patchwork

来比较结果
library(patchwork)

plot1/plot2

© www.soinside.com 2019 - 2024. All rights reserved.