13

我想在我的骑行图中画一条线来表示平均值。内置的分位数参数以我想要的样式画一条线,但在中位数。我怎样才能平均画一个,最好不使用geom_vline()在 ggplot 构建对象上采摘但留在 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"
  ) 

中线示例

4

1 回答 1

11

您可以为参数提供任意函数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 包(v0.3.0)于 2020-05-23 创建

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

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 包(v0.3.0)于 2020-05-23 创建

于 2020-05-23T18:31:15.333 回答