Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

r - ggplot density plot from data.frame that holds moments

Given a mean and a standard deviation, it is easy to plot a Gaussian density using ggplot2:

ggplot(data = data.frame(x = c(-3, 3)), aes(x)) +
       stat_function(fun = dnorm, args = list(mean = 0, sd = 1))

This example returns a density plot for the standard normal distribution. I have a data set that is somewhat more complex:

m = c(1, 1.5, 3, 3.5)     # means of gaussians
s = c(0.1, 0.3, 0.5, 0.7) # standard deviations of gaussians
g = c("A", "A", "B", "B") # group
v = c("X", "Y", "X", "Y") # class 


plot.df = data.frame(m = m,
                     s = s,
                     g = g,
                     v = v)

where m are the means of Gaussians and s are the corresponding standard deviations. I'd like to use facet_grid for the group variable g and color of the densities should depend on the class v. I can't wrap my head around how to achieve this without manually setting a legend for color and copy-pasting stat_function for every single density.

Edit: Just to be clear, the ideal solution should generalize to an arbitrary number of groups and in the best case also to an arbitrary number of classes.

question from:https://stackoverflow.com/questions/65887430/ggplot-density-plot-from-data-frame-that-holds-moments

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do the automated variant of manually creating multiple stat_functions() for every parameter.

For example, write a function that takes your values as input and produces a list of stat_function()s.

multidensity <- function(mu, sd, group, class, range = c(-3, 3)) {
  mapply(function(mu, sd, group, class) {
    stat_function(
      data = data.frame(group = group, class = class, x = range),
      aes(x = x, colour = class),
      fun = dnorm,
      args = list(mean = mu, sd = sd),
      inherit.aes = FALSE
    )
  }, mu = mu, sd = sd, group = group, class = class,
  SIMPLIFY = FALSE)
}

Then, simply call function when needed.

m = c(1, 1.5, 3, 3.5)     # means of gaussians
s = c(0.1, 0.3, 0.5, 0.7) # standard deviations of gaussians
g = c("A", "A", "B", "B") # group
v = c("X", "Y", "X", "Y") # class 

ggplot() +
  multidensity(m, s, g, v, range = c(0, 5)) +
  facet_wrap(~ group)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...