r - 在 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 的顺序?
解决方案
您可以调整stat_summary_2d()
以显示基于计算变量的文本after_stat()
。x轴的顺序可以通过设置limits
x-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 轴类别的数据集的最后一行,因此除非有意这样做,否则需要注意。
推荐阅读
- python - Pyglet 或 Pygame 哪个更适合 python?
- css - 如何将 CSS 应用于不在某个标签内的文本?只是#文本!通过使用 R,硒
- java - 为什么我们可以从 Java 中的另一个线程调用对象的方法?
- python - 相同的 GPU 卡 - 我可以在 FP32 和一个 FP64 上使用一种模型训练吗
- php - 如何处理 Audit Trail Laravel 中的关系?
- python - 单词列表python不和谐中的表情符号
- c - 我不断收到信号:尝试执行文件 I/O 时出现分段错误(核心转储)错误
- c - 在 C 中实现链表
- c++ - 为什么INCBIN`d var访问时会抛出错误?
- ignite - 我们如何配置 Ignite 以使用 kubernetes 集群的所有 CPU 内核