Customizing x-axis label of each numerical density plot with skewness and kurtosis value

Viewed 312

I plotted all numerical variables with density plot. I want to change the x-axis label of each plot with skewness and kurtosis value. Here's my sample code.

mtcars %>%
  keep(is.numeric) %>%                     
  gather() %>% 
  ggplot(aes(value)) +
  facet_wrap(~ key, scales = "free") + 
  geom_density(colour = "black", fill = "#56B4E9") +
  scale_y_continuous(name = "Density")

And I want the sample output below: enter image description here

1 Answers

Using the moments package to compute the kurtosis and skewness the desired result could be achieved like so:

  1. Using paste0 I put together the labels for each facet.
  2. Use the label as facetting variable
  3. Put the labels at the bottom (using strip.position = "bottom") and below the axis (using strip.placement = 'outside")
library(tidyr)
library(dplyr)
library(ggplot2)

mtcars %>%
  select_if(is.numeric) %>%                     
  gather() %>% 
  group_by(key) %>% 
  mutate(kurtosis = moments::kurtosis(value),
         skewness = moments::skewness(value),
         label = paste0(key, "\n", "Kurtosis: ", round(kurtosis, 2), ", Skewness: ", round(skewness, 2))) %>% 
  ggplot(aes(value)) +
  facet_wrap(~ label, scales = "free", ncol = 3, strip.position = "bottom") + 
  geom_density(colour = "black", fill = "#56B4E9") +
  scale_y_continuous(name = "Density") +
  theme(strip.placement = "outside")

Related