1

I'm looking for a way to create a scatterplot with marginal histograms. I found a solution using ggplot2 + cowplot (thanks @crsh):

library(ggplot2)
library(cowplot)

# Set up scatterplot
scatterplot <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
  geom_point(size = 3, alpha = 0.6) +
  guides(color = FALSE) +
  theme(plot.margin = margin())


# Define marginal histogram
marginal_distribution <- function(data, var, group) {
  ggplot(data, aes_string(x = var, fill = group)) +
    geom_histogram(bins = 30, alpha = 0.4, position = "identity") +
    # geom_density(alpha = 0.4, size = 0.1) +
    guides(fill = FALSE) +
    #theme_void() +
    theme(plot.margin = margin())
}

# Set up marginal histograms
x_hist <- marginal_distribution(iris, "Sepal.Length", "Species")
y_hist <- marginal_distribution(iris, "Sepal.Width", "Species") +
  coord_flip()

# Align histograms with scatterplot
aligned_x_hist <- align_plots(x_hist, scatterplot, align = "v")[[1]]
aligned_y_hist <- align_plots(y_hist, scatterplot, align = "h")[[1]]

# Arrange plots
plot_grid(
  aligned_x_hist
  , NULL
  , scatterplot
  , aligned_y_hist
  , ncol = 2
  , nrow = 2
  , rel_heights = c(0.2, 1)
  , rel_widths = c(1, 0.2)
)

I got:

enter image description here

Now, I have some questions:

a) How can I add a legend and a tittle without breaking the plot_grid?

b) The axes of the scatterplot does not match with the axes of the histograms. How can I solve this?

Regards!

  • Hi there, and welcome to SO. Since you've solved part - but not all - of your original question, it would be more clear if you edited your question, rather than supplying an answer for part of it. For example, focus the title of the question on just the part about the legend and title, edit the question to provide all your updated code that aligns the axes properly, and clarify that you are just looking to add a title and legend without disrupting the alignment. – phalteman Jul 22 '21 at 05:59

1 Answers1

0

Ok, I solve the axes problem:

I set xlim and ylim for the scatterplot based on the limits of the histograms:

scatterplot <- scatterplot +
  xlim(layer_scales(x_hist)$x$range$range) +
  ylim(layer_scales(y_hist)$x$range$range)

enter image description here

But I don't know how to add a tittle and a legend