gpt4 book ai didi

r - 将自定义数字添加到 ggplot 图例

转载 作者:行者123 更新时间:2023-12-04 11:30:23 30 4
gpt4 key购买 nike

我正在绘制一个 geom_tile 图,其中每个点都有一个特定的 p-value

图的绘制方式很好,p-value 限制在图例上。

我想添加到这个图例的是具有这个 p-value 的数据点的数量。

例子:

图例是这样的(每个值都有一个颜色):

0.05
0.04
0.03
0.02
0.01

我想要的是这样的:

0.05 58
0.04 34
0.03 85
0.02 54
0.01 10

如何将其添加到 ggplot2 图的图例中?

我尝试使用 geom_text 并将文本位置更改为图例,但没有成功。

更新

pl <- ggplot(df.new) + geom_tile(aes(fill=z, x, y)) + 
scale_fill_gradient(low="yellow", high="red", name="Legend1") +
stat_contour(breaks=c(0.001, 0.01, 0.05), aes(x=x, y=y, z=npvalue, colour=..level..)) +
scale_colour_gradient2(low="black", mid="black", high="green", labels=paste(levels(c(0.001, 0.01, 0.05))))

我有这个情节,我正在从 z 变量中正确绘制 geom_tile 然后我根据 p- 绘制 stat_contour值(value)。我想编辑基于 p-valuestat_contour 颜色的标签,就像我最初的问题一样,但我遇到了这个错误:

Error in scale_labels.continuous(scale, breaks) : 
Breaks and labels are different lengths

我的绘图问题出在哪里??

最佳答案

您可以为 fill 颜色指定图例的 labels

一个示例数据集:

set.seed(1)
dat <- data.frame(x = rep(1:5), y = rep(1:10),
z = factor(sample(seq(0.01, 0.05, 0.01), 100, TRUE)))

table函数统计dat$z的不同值:

table(dat$z)

# 0.01 0.02 0.03 0.04 0.05
# 13 25 19 26 17

剧情:

library(ggplot2)
ggplot(dat) +
geom_tile(aes(x = x, y = y, fill = z)) +
scale_fill_discrete(labels = paste(levels(dat$z), table(dat$z)))

在最后一行,创建了图例的labels

enter image description here

关于r - 将自定义数字添加到 ggplot 图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20808881/

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