I am trying to make scatter plots in ggplot.
I have this code:
library(ggplot2)
A <- c(0.723598, 0.913736, 0.841558, 0.797557, 0.651486, 0.682145, 0.891233, 0.771894, 0.800201, 0.835619)
B <- c(28.525191, 31.348356, 31.497754, 24.501088, 25.188794, 27.167893, 32.734721, 26.043711, 29.248189, 30.007202)
correlation <- cor(A, B)
data_scatter <- data.frame(A = A, B = B)
# Create ggplot
ggplot(data_scatter, aes(x = A, y = B)) +
geom_point(size = 7, color = "#56B4E9") +
xlim(0.6, 0.93) +
ylim(24, 32) +
geom_smooth(method = "lm", color = "black", se = FALSE, size = 2.5) +
geom_text(x = 0.67, y = 31, label = paste0('r = ', round(correlation, 2)),
size = 20, check_overlap = TRUE) +
labs(x = "", y = "", title = "") +
theme_bw() +
theme(
panel.border = element_rect(color = "black", size = 2),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 54, color = "black"),
axis.text.y = element_text(size = 54, color = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
aspect.ratio = 1,
plot.margin = unit(c(1, 1, 6, 6), "cm"))
if you see, I am plotting the axis texts. This way plot occupies a certain area.
But if I set the axis.text.x and axis.text.x as element_blank() , the scatter plot occupies more area (takes the space freed from axis texts). See below.

My question is, how can I force the plot to occupy the same area regardless of the axis texts and titles? So the plot doesn't get bigger and smaller when axis texts/titles are removed or added.
I have tried coord_fixed(ratio = 1) but it didn't help.
set_panel_size() from the egg package will let you fix the panel size.
However if you also want to fix the panel position it’ll be a bit more involved.
library(ggplot2)
library(egg)
grid.arrange(
grobs = lapply(
list(
ggplot(mtcars, aes(wt, mpg)) + geom_point(),
ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme(axis.text = element_blank())
),
function(p) {
set_panel_size(p, width = unit(3, "in"), height = unit(2, "in"))
}
),
ncol = 2
)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With