[英]Paste mean values on geom_tile plot (ggplot in R)
I am using this code:我正在使用这段代码:
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()
How can I paste the mean values as text on each tile?如何将平均值作为文本粘贴到每个图块上? I tried
+ geom_text(mtcars, aes(vs, variable, label=mean))
, but that does not work.我试过
+ geom_text(mtcars, aes(vs, variable, label=mean))
,但这不起作用。
Also, how can I reverse the order of 0 and 1 on the x axis?另外,如何在 x 轴上颠倒 0 和 1 的顺序?
You can tweak stat_summary_2d()
to display text based on computed variables with after_stat()
.您可以使用 after_stat() 调整 stat_summary_2d
after_stat()
stat_summary_2d()
以根据计算变量显示文本。 The order of the x-axis can be determined by setting the limits
argument of the x-scale. 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"))
Created on 2021-04-06 by the reprex package (v1.0.0)由代表 package (v1.0.0) 于 2021 年 4 月 6 日创建
Also note that the geom_tile()
just plots the last row of the dataset belonging to the x- and y-axis categories, so unless that is intended, it is something to be aware of.另请注意,
geom_tile()
仅绘制属于 x 轴和 y 轴类别的数据集的最后一行,因此除非有意这样做,否则需要注意。
You can do the processing work outside of ggplot to produce:您可以在 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)
Created on 2021-04-06 by the reprex package (v1.0.0)由代表 package (v1.0.0) 于 2021 年 4 月 6 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.