The following data frame contains three normal distributions with different mean and standard deviation separated by group. This data will be used in all the examples of this tutorial.
geom_density
In order to create a density plot by group in ggplot you need to input the numerical variable and specify the grouping variable in color
(or colour
) argument inside aes
and use geom_density
function.
The default color palette for the lines can be customized with scale_color_manual
(or scale_color_brewer
, for instance). You can also change the width and line type of the curves with lwd
and linetype
, respectively.
If you also set the categorical variable to fill
inside aes
the areas under the curves will be filled with a color. Note that you can remove colour = group
or set a custom color if you don’t want to color the lines by group.
Transparency and custom colors
You can modify the transparency of the areas with the alpha
argument of geom_density
and set custom colors with scale_fill_manual
.
Remove the lines
If you want to get rid of the lines and only show the area you can set color = NA
inside geom_density
.
Custom title
The default title (the name of the categorical variable) can be customized with the following code.
Custom labels
You can also set custom key labels if you don’t want to use the name of your categories. Note that you can use scale_fill_hue
if you only want to change the labels, but use the labels
argument of scale_fill_manual
if you also need to change the fill colors.
Remove the legend
If you want to get rid of the legend, which appears by default, you can set its position to "none"
.
See also