Reputation: 273
I have a line plot p
generated from a long/melted dataframe DF
.
I would now like to add a marginal density plot along the y axis to show the distribution of score
at t5
. I have just come across ggExtra::ggMarginal
, but the tutorials I've found only seem to work with scatter plots and not with subsets of the main plot's data.
Here's the structure of DF
:
> str(DF)
'data.frame': 600 obs. of 3 variables:
$ ID : int 1 2 3 4 5 6 7 8 9 10 ...
$ variable: Factor w/ 6 levels "t0","t1","t2",..: 1 1 1 1 1 1 1 1 1 1 ...
$ value : num 0.737 0.33 0.526 0.737 0.357 ...
And here's my line plot p
:
I tried this...
# the code that produces the line plot above
p <- ggplot(DF, aes(x = variable, y = value, color = ID, group = ID))+
geom_line() +
theme_bw() +
ylim(0, 1) +
labs(x = "Time", y = "Score", color = "ID", subtitle = "")+
theme(legend.position = "none")
#trying to add marginal density plot based on subsetted t5 scores
p <- ggMarginal(p, data = DF[which(DF$variable == "t5"),], x = value, type = "density")
But it throws this error: Error: No geom_point layer was found in your scatter plot
Does ggMarginal
only work with scatter plots? How might I add a marginal density plot of score
at t5
to the right side y axis?
Upvotes: 1
Views: 1154
Reputation: 273
I'll go ahead and answer my own question following @ricoderks comment.
It seems the solution is to just plot an invisible scatter plot. Here's the code that worked:
p <- ggplot(DF, aes(x = variable, y = value, color = ID, group = ID))+
geom_line() +
geom_point(data = DF[which(DF$variable == "t5"),], alpha = 0)+
theme_bw() +
ylim(0, 1) +
labs(x = "Time", y = "Score", color = "ID", subtitle = "")+
theme(legend.position = "none")
p <- ggMarginal(p, type = "density", margins = "y", size = 6, color = "steelblue4")
Upvotes: 1