Skip to content

Instantly share code, notes, and snippets.

@lukereding
Created August 24, 2017 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukereding/9bacdc6e42dff610b91d3cdd94a5eb1a to your computer and use it in GitHub Desktop.
Save lukereding/9bacdc6e42dff610b91d3cdd94a5eb1a to your computer and use it in GitHub Desktop.
cowplot, marginal plots, and coord_flip
library(ggplot2)
library(cowplot) # github version
# create dataframe with x and y with different ranges
df <- data.frame(x = rnorm(20, mean = 5, sd = 2), y = rnorm(20, mean = 20, sd = 5))
# create scatterplot
p <- ggplot(df, aes(x = x, y = y)) +
geom_point()
# create density plot, clone x-axis and `coord_flip()`ing
y_density <- axis_canvas(p, axis = "x") +
geom_density(data = df, aes(x = x)) +
coord_flip()
# make combined plot
combined_plot <- insert_yaxis_grob(p, y_density, position = "right")
# range limits are wrong so the plot on the right is not shown
ggdraw(combined_plot)
@clauswilke
Copy link

Line 13 I think should be geom_density(data = df, aes(x = y)) +

@clauswilke
Copy link

This seems to work now. Do a git pull and try.

library(ggplot2)
library(cowplot) # github version

# create dataframe with x and y with different ranges
df <- data.frame(x = rnorm(20, mean = 5, sd = 2), y = rnorm(20, mean = 20, sd = 5))

# create scatterplot
p <- ggplot(df, aes(x = x, y = y)) +
  geom_point()

# create density plot, clone x-axis and `coord_flip()`ing
y_density <- axis_canvas(p, axis = "x", coord_flip = TRUE) +
  geom_density(data = df, aes(x = y)) +
  coord_flip()

# make combined plot
combined_plot <- insert_yaxis_grob(p, y_density, position = "right")

# range limits are wrong so the plot on the right is not shown
ggdraw(combined_plot)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment