This is my followup question on my previous post on the same subject available in Superimpose one ggplot on another.
I want to super-impose one ggplot
onto another on 100% basis. Below is my code, based on the accepted answer from @TimG
library(ggplot2)
library(cowplot)
library(dplyr)
set.seed(1)
data = data.frame(x = rnorm(1000), y = rnorm(1000))
ggdraw() +
draw_plot(ggplot(data, aes(x = x, y = y)) +
geom_point(color = 'black') +
scale_y_continuous(limits = c(-4, 4), breaks = seq(-4, 4, by = 1)) +
scale_x_continuous(limits = c(-4, 4), breaks = seq(-4, 4, by = 1)) ) +
draw_plot(ggplot(data %>% mutate(x = x + .05, y = y + .05), aes(x = x, y = y)) +
geom_point(color = 'red') +
scale_y_continuous(limits = c(-4, 4), breaks = seq(-4, 4, by = 1)) +
scale_x_continuous(limits = c(-4, 4), breaks = seq(-4, 4, by = 1)) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_rect(fill = 'transparent'), plot.background = element_rect(fill = 'transparent'), axis.text.y=element_blank(), axis.ticks.y=element_blank()),
x = 0.00, y = 0.0, width = 1, height = 1)
However as you can see, the second ggplot
appears to be slightly right aligned as compared to the first ggplot
. My input x = 0.00, y = 0.0, width = 1, height = 1
does not seem to be considered completely.
Can you please help to understand why the second ggplot
is slighly right-aligned? How can I fix it to have 100% match with the first ggplot
?
The typically failure cause for this will be that the plots differ in the spacing needed for axis text, such as in your example where you have removed the axis text from one plot. ggplot2 and cowplot have no way to know that the plot without axis text should be created as if it were really a plot with axis text, such that it would align with another layer. The default behavior will be to extend the panel to use some of the dead space no longer needed by your axis text. To avoid this, you can keep the axis text layer but make the text transparent (in theme()
), or the labels be blanks (in scale_x/y_*()
) .
In the couple cases I tried with different geoms/scales, absent the issue above, the default settings worked fine. For example, adding this as the second layer:
... +
draw_plot(ggplot(mtcars, aes(as.factor(cyl), mpg)) +
geom_boxplot() +
theme(axis.text.x = element_text(color = "#FF000000"),
plot.background = element_rect(fill = NA),
panel.background = element_rect(fill = NA, color = "red")),
x = 0.00, y = 0.0, width = 1, height = 1)
gave me the magnificent plot below, which is aligned as to where the axis titles and axis labels go, as well as the plot "panel" extent. You'll note that by making my 2nd plot's axis.text.x
be transparent red ("#FF000000" encoded in hex as #RRGGBBAA), the text still takes up the space it should, but is not shown.
If this does not work for your cases, please include an example that demonstrates the issue.