Home > Net >  ggplot(data = df1) with added ggMarginal (data = df2)
ggplot(data = df1) with added ggMarginal (data = df2)

Time:01-28

I aim to create a ggplot with Date along the x axis, and jump height along the y axis. Simplistically, for 1 athlete in a large group of athletes, this will allow the reader to see improvements in jump height over time.

Additionally, I would like to add a ggMarginal(type = "density") to this plot. Here, I aim to plot the distribution of all athlete jump heights. As a result, the reader can interpret the performance of the primary athlete in relationship to the group distribution.

For the sack of a reproducible example, the Iris df will work.

'''

library(dplyr)
library(ggplot2)
library(ggExtra)

df1 <- iris %<%
       filter(Species == "setosa")

df2 <- iris


 #I have tried as follows, but a variety of error have occurred:

 ggplot(NULL, aes(x=Sepal.Length, y=Sepal.Width)) 
 geom_point(data=df1, size=2) 
 ggMarginal(data = df2, aes(x=Sepal.Length, y=Sepal.Width), type="density", margins = "y", size = 6)
 

'''

Although this data frame is significantly different than mine, in relation to the Iris data set, I aim to plot x = Sepal.Length, y = Sepal.Width for the Setosa species (df1), and then use ggMarginal to show the distribution of Sepal.Width on the y axis for all the species (df2)

I hope this makes sense!

Thank you for your time and expertise

CodePudding user response:

As far as I get it from the docs you can't specify a separate data frame for ggMarginal. Either you specify a plot to which you want to add a marginal plot or you provide the data directly to ggMarginal.

But one option to achieve your desired result would be to create your density plot as a separate plot and glue it to your main plot via patchwork:

library(ggplot2)
library(patchwork)

df1 <- subset(iris, Species == "setosa")
df2 <- iris

p1 <- ggplot(df1, aes(x = Sepal.Length, y = Sepal.Width))  
  geom_point(size = 2)

p2 <- ggplot(df2, aes(y = Sepal.Width))  
  geom_density()  
  theme_void()

p1   p2  
  plot_layout(widths = c(6, 1))

  • Related