gpt4 book ai didi

R:ggplot2,如何注释面板图每个面板上的汇总统计数据

转载 作者:行者123 更新时间:2023-12-03 01:18:45 24 4
gpt4 key购买 nike

如何使用 R 中的 ggplot2 在以下绘图的每个面板中添加标准差的文本注释(例如 sd = sd_value)?

library(datasets)
data(mtcars)
ggplot(data = mtcars, aes(x = hp)) +
geom_dotplot(binwidth = 1) +
geom_density() +
facet_grid(. ~ cyl) +
theme_bw()

我想发布情节的图像,但我没有足够的代表。

我认为“geom_text”或“annotate”可能有用,但我不太确定如何用。

最佳答案

如果您想改变每个方面的文本标签,您将需要使用geom_text。如果您希望每个方面都显示相同的文本,可以使用annotate

p <- ggplot(data = mtcars, aes(x = hp)) + 
geom_dotplot(binwidth = 1) +
geom_density() +
facet_grid(. ~ cyl)

mylabels <- data.frame(
cyl = c(4, 6, 8),
label = c("first label", "second label different", "and another")
)

p + geom_text(x = 200, y = 0.75, aes(label = label), data = mylabels)

### compare that to this way with annotate

p + annotate("text", x = 200, y = 0.75, label = "same label everywhere")

现在,如果您确实想要在此示例中使用 cyl 计算标准差,我可能会先使用 dplyr 进行计算,然后使用 完成计算geom_text 像这样:

library(ggplot2)
library(dplyr)

df.sd.hp <- mtcars %>%
group_by(cyl) %>%
summarise(hp.sd = round(sd(hp), 2))

ggplot(data = mtcars, aes(x = hp)) +
geom_dotplot(binwidth = 1) +
geom_density() +
facet_grid(. ~ cyl) +
geom_text(
data = df.sd.hp,
aes(label = paste0("SD: ", hp.sd))
x = 200, y = 0.75
)

关于R:ggplot2,如何注释面板图每个面板上的汇总统计数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com