Ggplot and grid: find the relative x and y positions of a point in ggplot grob
I am piling multiple ggplot plots using gridviews, a necessity (I believe) because I want to rotate the plot, which is not possible in standard ggplot and maybe even in the gridExtra package.
I want to draw a line on two plots to make the correlation more clear. But to know exactly where the lines are, I need the relative positions of the point in the ggplot (grob?) Plot.
I made the following example:
require(reshape2)
require(grid)
require(ggplot2)
datamat <- matrix(rnorm(50), ncol=5)
cov_mat <- cov(datamat)
cov_mat[lower.tri(cov_mat)] <- NA
data_df <- melt(datamat)
cov_df <- melt(cov_mat)
plot_1 <- ggplot(data_df, aes(x=as.factor(Var2), y=value)) + geom_boxplot()
plot_2 <- ggplot(cov_df, aes(x=Var1, y=Var2, fill=value)) +
geom_tile() +
scale_fill_gradient(na.value="transparent") +
coord_fixed() +
theme(
legend.position="none",
plot.background = element_rect(fill = "transparent",colour = NA),
panel.grid=element_blank(),
panel.background=element_blank(),
panel.border = element_blank(),
plot.margin = unit(c(0, 0, 0, 0), "npc"),
axis.ticks=element_blank(),
axis.title=element_blank(),
axis.text=element_text(size=unit(0,"npc")),
)
cov_heatmap <- ggplotGrob(plot_2)
boxplot <- ggplotGrob(plot_1)
grid.newpage()
pushViewport(viewport(height=unit(sqrt(2* 0.4 ^2), 'npc'),
width=unit(sqrt(2* 0.4 ^2), 'npc'),
x=unit(0.5, 'npc'),
y=unit(0.63, 'npc'),
angle=-45,
clip="on")
)
grid.draw(cov_heatmap)
upViewport(0)
pushViewport(viewport(height=unit(0.5, 'npc'),
width=unit(1, 'npc'),
x=unit(0.5, 'npc'),
y=unit(0.25, 'npc'),
clip="on")
)
grid.draw(boxplot)
How do I find the relative x and y positions (let's say) of the first boxplot? and also the relative x and y positions of the triangular covariance matrix.
I know I need to examine grob objects boxplot
, but I don't know how to find the relevant data there.
EDIT:
I was asked to give an example of a plot with manually added lines like below:
The lines come from points in the lower plot to blocks in the upper plot.
source to share
No one has answered this question yet
Check out similar questions: