【问题标题】:Paste mean values on geom_tile plot (ggplot in R)在 geom_tile 图上粘贴平均值(R 中的 ggplot)
【发布时间】:2021-07-02 05:03:33
【问题描述】:

我正在使用此代码:

 library(tidyverse)
 library(reshape)
 mtcars <- melt(mtcars, id="vs")
 mtcars$vs <- as.character(mtcars$vs)
 ggplot(mtcars, aes(x=vs, y=variable, fill=value)) + 
      geom_tile()

如何将平均值作为文本粘贴到每个图块上?我试过 + geom_text(mtcars, aes(vs, variable, label=mean)),但不起作用。

另外,我怎样才能颠倒x轴上0和1的顺序?

【问题讨论】:

    标签: r ggplot2 tidyverse geom-text geom-tile


    【解决方案1】:

    您可以调整stat_summary_2d() 以使用after_stat() 根据计算变量显示文本。 x轴的顺序可以通过设置x-scale的limits参数来确定。

    suppressPackageStartupMessages({
      library(tidyverse)
      library(reshape)
      library(scales)
    })
    
    mtcars <- melt(mtcars, id="vs")
    mtcars$vs <- as.character(mtcars$vs)
    
    ggplot(mtcars, aes(x=vs, y =variable, fill = value)) +
      geom_tile() +
      stat_summary_2d(
        aes(z = value, 
            label = after_stat(number(value, accuracy = 0.01))),
        fun = mean,
        geom = "text"
      ) +
      scale_x_discrete(limits = c("1", "0"))
    

    reprex package (v1.0.0) 于 2021-04-06 创建

    另请注意,geom_tile() 仅绘制属于 x 轴和 y 轴类别的数据集的最后一行,因此除非有意这样做,否则需要注意。

    【讨论】:

      【解决方案2】:

      你可以在ggplot之外做处理工作来生产:

      library(ggplot2)
      library(dplyr)
      library(tidyr)
      
      df <- 
        mtcars %>%
        pivot_longer(-vs) %>% 
        group_by(vs, name) %>% 
        mutate(vs = factor(vs, levels = c(1, 0), ordered = TRUE),
               mean = round(mean(value), 2))
      
      
      ggplot(df, aes(x=vs, y=name, fill=value)) + 
        geom_tile() +
        geom_text(aes(vs, name, label=mean), colour = "white", check_overlap = TRUE)  
      

      reprex package (v1.0.0) 于 2021-04-06 创建

      【讨论】:

      • 谢谢你,彼得。了不起! :)
      猜你喜欢
      • 2023-04-03
      • 2018-11-14
      • 2019-04-02
      • 1970-01-01
      • 2020-04-18
      • 2012-08-31
      • 2014-02-27
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多