首页 > 解决方案 > 在 geom_tile 图上粘贴平均值(R 中的 ggplot)

问题描述

我正在使用这段代码:

 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 的顺序?

标签: rggplot2tidyversegeom-textgeom-tile

解决方案


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

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 包(v1.0.0)于 2021-04-06 创建

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


推荐阅读