【问题标题】:How to add the x intercept from geom_vline in density plot as a label?如何在密度图中添加来自 geom_vline 的 x 截距作为标签?
【发布时间】:2019-09-25 14:17:50
【问题描述】:

我正在创建一个密度图并对其进行刻面。 假设我有 4 个变量组,使用该变量对其进行分面会生成 4 个密度图。

对于每个密度图,我画了一条代表平均值的垂直线。

但是,需要用眼睛观察 x 轴和垂直线的交点,才能大致了解平均值是多少。

我要为每个密度图创建,我还想在绘图区域中将其平均值显示为标签。

下面的示例代码


x <- rnorm(n = 100, mean = 10, sd = 1)
y <- rnorm(n = 100, mean = 20, sd = 1)
z <- rnorm(n = 100, mean = 40, sd = 1)



df <- as_tibble(cbind(
  c(x,y,z), 
  c(rep('x',length(x)), rep('y',length(y)), rep('z',length(z))),
  c(rep('a',length(x)/2), rep('b',length(x)/2))))

df$V1 <- as.numeric(df$V1)

df <- df %>% group_by(V2, V3) %>%
  summarise(mumean = mean(V1)) %>%
  right_join(df)


df %>%
  ggplot(aes(x = V1, color = V2)) + 
  geom_density(aes(fill = V2)) + facet_grid(V3 ~ V2) + theme_bw() +
  geom_vline(data = df, aes(xintercept = mumean))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    一种方法是预先计算方法并使用这些方法来提供geom_vlinegeom_text

    library(dplyr)
    iris_means <- iris %>%
      group_by(Species) %>%
      summarize(mean = mean(Sepal.Length))
    
    ggplot(iris, aes(Sepal.Length)) +
      geom_density() +
      geom_vline(data = iris_means, aes(xintercept = mean)) +
      geom_text(data = iris_means, aes(x = mean, label = mean), 
                 y = 0.1, angle = 90, vjust = -0.2) +
      facet_wrap(~Species) 
    

    【讨论】:

    • 这太棒了:)。有点切题,有什么技巧可以改变 geom_text 中的“y”,使其自动适合自己吗?我的实际数据有另一个我需要循环的变量。然而,它们具有不同的密度。如果我使用修复'y',有时它会定位得太高或太低..
    • 这可能有一个ggrepel 解决方案,但我不确定一种优雅的方法可以使文本专门从密度图边缘排斥。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多