使用偏度和峰度值自定义每个数值密度图的 x 轴标签

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

我用密度图绘制了所有数值变量。我想用偏度和峰度值更改每个图的 x 轴标签。这是我的示例代码。

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

我想要下面的示例输出:

使用 moments 包来计算 kurtosisskewness 可以得到想要的结果,如下所示:

  1. 使用 paste0 我将每个方面的标签放在一起。
  2. 使用 label 作为构面变量
  3. 将标签放在底部(使用strip.position = "bottom")和轴下方(使用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")