Search code examples
rplotggplot2density-plot

Adding "all" category to ggplots2 plot


Question

Suppose I want to make density plots for each categories with an additional category of "all" points. How would I go about creating such a figure? Is there a way other than duplicating all points with an "all" category?

Example

library('ggplot2')
fig <- ggplot(iris, aes(x = Sepal.Length, color = Species)) + 
       stat_density(geom = "line", position = "identity")

which will output the following figure:

http://127.0.0.1:16553/chunk_output/8D7C71B83681FBD4/144E3B0/cby49jvbfsi3m/00001b.png

However, I would like to include another line that contains all of the points.


Solution

  • ggplot(iris, aes(x = Sepal.Length, color = Species)) + 
      stat_density(geom = "line", position = "identity") + 
      stat_density(aes(x = Sepal.Length, color = "all"), geom = "line")
    

    enter image description here