问题
I have this ggplot
ggplot(data = ph, aes(x = index1)) + geom_density()
and I would like to add a normal distribution with the same mean (= 2.71)
and standard Deviation (= 0.61)
.
I created the normal distribution with:
nd1 <- rnorm(n = 100000, mean = 2.71), sd = 0.61)
nd1plot <- qplot(nd1, geom = "density") + theme_classic() + ggtitle("Normalverteilung")
But now I don't know how to add it to my existing plot. Can anyone help me with this issue?
回答1:
ggplot2
has stat_function() for this kind of thing, but my solution takes a more manual approach in the name of clarity. You didn't provide an example of your data, but you should be able to replace mtcars$mpg
with whatever column or vector you want.
library(tidyverse) # Gives us ggplot2 and lots of other goodies
# Choose your variable of interest
dta <- mtcars$mpg %>%
as_tibble() # USing a tibble instead of a dataframe makes the data more predictable
# Generate normal data based on dta
norm_data <-
rnorm(
n = length(dta),
mean = mean(dta$value),
sd = sd(dta$value)
)
# Create the plot
ggplot(dta, aes(x = value)) +
geom_density() +
geom_density(aes(norm_data), color = "darkgray", linetype = "dashed") +
theme_classic()
来源:https://stackoverflow.com/questions/40868904/plot-normal-distribution-into-existing-plot