【问题标题】:R: ggplot2: how to separate labels in stat_summaryR:ggplot2:如何在 stat_summary 中分隔标签
【发布时间】:2020-03-22 08:57:25
【问题描述】:

我尝试使用stat_summary 函数和我编写的自定义函数在条形上方绘制标签。共有三个条,每个条都应分别标有字母 a:c。但是,不是每个条都放置一个标签,而是将所有三个标签放在彼此的顶部:

codes <- c ("a", "b", "c")

simple_y <- function(x) {
        return (data.frame (y = mean (x) + 1, label = codes))
        }


    ggplot (iris, mapping = aes (x = Species, y = Sepal.Length)) +
        geom_bar (stat = "summary", fun.y = "mean", fill = "blue", width = 0.7, colour = "black", size = 0.7) +
        stat_summary (fun.data = simple_y, geom = "text", size = 10)

我明白为什么这不起作用:每次回收 simply_y-function 时,它都会看到整个 codes - 向量。但是,我不知道如何告诉 R 将三个标签分开。是否可以告诉 R 在回收函数时随后使用输入向量的第 n 个元素?

有人有好的提示吗?

【问题讨论】:

    标签: r ggplot2 plot label


    【解决方案1】:

    我会考虑做这样的事情:

    labels <- 
      tibble(
        Species = factor(c("setosa", "versicolor", "virginica")),
        codes = c("a", "b", "c")
      )
    
    iris %>% 
      group_by(Species) %>% 
      summarize(Mean = mean(Sepal.Length)) %>% 
      ungroup() %>% 
      left_join(labels, by = "Species") %>% 
      ggplot(aes(x = Species, y = Mean)) +
      geom_col(fill = "blue", width = 0.7, color = "black", size = 0.7) +
      geom_text(aes(y = Mean + 0.3, label = codes), size = 6, show.legend = FALSE)
    

    首先,您可以分别生成带有均值的数据框,从而避免了对 geom_bar 和 stat_summary 的需要。然后将手动标签/代码加入到该汇总数据框后,使用 geom_text 添加它们非常简单。

    【讨论】:

    • 这个解决方案很有效,我当然喜欢它。但是,出于我的目的,我更喜欢一种无需在绘图前准备数据的解决方案。
    • @yenats 这可能是 ggplot 中最关键的一步,将数据转换为适合绘图目的的形状。您很可能需要针对不同的绘图以不同的方式重塑相同的数据 - 数据形状不是固定的,而 R 可以很容易地重塑。实际上 - 当您允许自己重塑数据时,您的生活会变得更加轻松:)
    • 我得出的结论是,确实,重塑数据似乎是最佳实践。感谢您的支持!
    猜你喜欢
    • 2020-11-21
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    相关资源
    最近更新 更多