R ggrides 包绘制平均线(NOT MEDIAN)

R ggrides package drawing mean line (NOT MEDIAN)

我想在我的路线图上画一条线作为平均值。内置分位数参数以我想要的样式绘制一条线,但位于 中位数 处。我怎样才能平均画一个,最好不使用geom_vline() or 但留在ggridges生态中?

library(tidyverse)
library(ggridges)

#adding a column for the mean of each Species of the iris dataframe
iris_meaned <- iris %>%
  group_by(Species) %>% 
  mutate(mean_petal_len = mean(Petal.Length)) %>% 
  ungroup()


iris_meaned %>% 
  ggplot() +
  geom_density_ridges(
    aes(x = Petal.Length, y = Species, fill = Species), 
    quantile_lines = T, quantiles = 2 #adding lines for the median
  ) +
  geom_text(
    aes(x = mean_petal_len, y = Species, label = round(mean_petal_len, 2)),
    size = 2, nudge_x = 0.03, nudge_y = 0.35
  ) +
  theme_classic() +
  theme(
    axis.title = element_blank(), 
    legend.position = "None"
  ) 

您可以为参数 quantile_fun 提供任意函数。该函数必须将数值向量作为第一个参数,将分位数作为第二个参数。但是忽略第二个参数也没关系。 mean() 函数满足这些条件,因此 quantile_fun = mean 在均值处创建垂直线。

请注意,在您的示例中,您一遍又一遍地绘制文本标签。我已经修复了代码,因此它可以正常工作。

library(tidyverse)
library(ggridges)

iris_meaned <- iris %>%
  group_by(Species) %>% 
  summarize(mean_petal_len = mean(Petal.Length))

ggplot(iris) +
  geom_density_ridges(
    aes(x = Petal.Length, y = Species, fill = Species), 
    quantile_lines = T, quantile_fun = mean)  + 
  geom_text(
    data = iris_meaned,
    aes(x = mean_petal_len, y = Species, label = round(mean_petal_len, 2)),
    size = 2, nudge_x = 0.03, nudge_y = 0.35
  ) +
  theme_classic() +
  theme(
     axis.title = element_blank(), 
     legend.position = "None"
  ) 
#> Picking joint bandwidth of 0.155

reprex package (v0.3.0)

于 2020-05-23 创建

为了提供第二个示例,让我们在均值和均值 +/- 1 标准差处画线。我们可以通过定义函数 meansd() 来做到这一点 returns 这三个值的向量。

library(tidyverse)
library(ggridges)

meansd <- function(x, ...) {
  mean <- mean(x)
  sd <- sd(x)
  c(mean - sd, mean, mean + sd)
}

ggplot(iris) +
  geom_density_ridges(
    aes(x = Petal.Length, y = Species, fill = Species), 
    quantile_lines = T, quantile_fun = meansd)  + 
  theme_classic() +
  theme(
    axis.title = element_blank(), 
    legend.position = "None"
  ) 
#> Picking joint bandwidth of 0.155

reprex package (v0.3.0)

于 2020-05-23 创建