I’m having problems creating this plot so that all the 4 components have the right proportions. I would like to rotate the diagonal line (in the right corner) in a specific way so that it is exactly placed diagonally at the same height as the trendline of the basis plot with the two conditions x1 and x2. In other words, the dashed line of the upper right “plot” is supposed to continue the trendline of the basis plot. Then when I enlarge or minimize the plot, it shouldn’t lose these proportions.
How the plot currently looks like:
enter image description here
When I zoom in, the proportions change:
enter image description here
How it should look like regardless of any device changements:
enter image description here
The other two graphs are supposed to be placed right alongside the basis plot (as in the second image). They aren’t relevant for the question.
Here the code to have a reproducible example:
library("tibble")
library("ggplot2")
library("patchwork")
# Simulate data
rho <- 0.7
sigma <- diag(2) * (1-rho) + rho
mu <- c(0.7, 0)
set.seed(2341)
uncorrelated <- mvtnorm::rmvnorm(50, mean = mu, sigma = sigma) |>
data.frame()
# Create components
scatterplot_uncorrelated <- ggplot(uncorrelated) +
aes(x = X1, y = X2) +
geom_abline(
intercept = 0
, slope = 1
, linetype = "22"
, color = grey(0.7)
) +
geom_point(
aes(fill = ifelse(X2 > X1, "weird", "expected"))
, pch = 21
, color = "white"
, size = 3
) +
scale_fill_manual(values = c("1", "2")) +
coord_equal(xlim = c(-3, 4), ylim = c(-3, 4)) +
guides(fill = "none")
x_den <- ggplot(uncorrelated) +
aes(x = X1) +
stat_density(color = "black", fill = NA) +
lims(x = c(-3, 4)) +
theme_void(base_size = 14)
y_den <- ggplot(uncorrelated) +
aes(y = X2) +
stat_density(color = "black", fill = NA) +
lims(y = c(-3, 4)) +
theme_void(base_size = 14)
diag_den <- ggplot(uncorrelated) +
geom_path(aes(x = x, y = y), data = tibble(x = c(0, dnorm(0, mean =
0.7, sd = 1) * 5), y = x), linetype = "22", color = grey(0.7)) +
geom_path(aes(x = x, y = y), data = tibble(x = c(-2.85, 2.75), y =
c(2.85, -2.75)), size = 0.5) +
coord_fixed(clip = "off") +
theme_void()
# Putting together the 3 graphics and a placeholder
(x_den +
plot_spacer() + # Placeholder for the differential diagram at the
right upper corner
scatterplot_uncorrelated +
y_den +
plot_layout(width = c(1, 0.3), height = c(0.3, 1)) # Einstellung der
relativen Plotgrößen
) |>
cowplot::ggdraw() +
# plot the the differential diagram on the top
inset_element(
diag_den
, left = 0.61 -0.025
, bottom = 0.61 -0.025,
, right = 1 -0.025
, top = 1 -0.025
, align_to = "plot"
)
I would be glad for any help, since I’m new to plotting in R and also new to Stack Overflow!
Nancy
I tried many things for example changing the sizes and proportions of the other two plots but it doesn’t work as I imagined it.
meth_hiwi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.