I have 2 normal probability plots
as below
library(ggplot2)
# Plot 1
ggplot(data.frame(x = c(-4, 4)), aes(x))
stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col='red')
stat_function(fill='red', fun = dnorm, xlim = c(-4, -1), geom = "area")
stat_function(fill='red', fun = dnorm, xlim = c(-1, 4), geom = "area", alpha = 0.3)
# Plot 2
ggplot(data.frame(x = c(-4, 4)), aes(x))
stat_function(fun = dnorm, args = list(mean = 0, sd = 2), col='blue')
stat_function(fill='blue', fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-4, -1), geom = "area")
stat_function(fill='blue', fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-1, 4), geom = "area", alpha = 0.3)
Individually they are just fine. However I wanted to combine these 2 plots and place them in same plot window with same x-axis
.
I also want to add a legend
based on fill
color in the combined plot to distinguish them.
Is there any way to achieve this with ggplot
?
Any pointer will be very helpful
CodePudding user response:
You could combine both the stat_function
s and create two with an aes
for your fill
to create a legend with scale_fill_manual
like this:
library(ggplot2)
ggplot(data.frame(x = c(-4, 4)), aes(x))
stat_function(fun = dnorm, args = list(mean = 0, sd = 1), col='red')
stat_function(fun = dnorm, xlim = c(-4, -1), geom = "area", aes(fill = "plot 1"))
stat_function(fill='red', fun = dnorm, xlim = c(-1, 4), geom = "area", alpha = 0.3)
stat_function(fun = dnorm, args = list(mean = 0, sd = 2), col='blue')
stat_function(fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-4, -1), geom = "area", aes(fill = "plot 2"))
stat_function(fill='blue', fun = dnorm, args = list(mean = 0, sd = 2), xlim = c(-1, 4), geom = "area", alpha = 0.3)
scale_fill_manual(name = "Legend", values = c("red", "blue"))
Created on 2022-12-31 with reprex v2.0.2