gpt4 book ai didi

r - 将 geom_text 颜色与绘图中的元素匹配并删除 ggplot2 中的图例标题

转载 作者:行者123 更新时间:2023-12-05 00:55:53 34 4
gpt4 key购买 nike

我有两个问题:
- 如何使 geom_text 中的颜色与 geom_point 中的颜色相同?
- 如何删除图例标题?

假设有以下数据集:

library(ggplot2)
library(reshape2)

speed <- c(0, seq(from = 30, to = 330, by = 60))
power1 <- c(75, 85, 88, 85, 94, 92, 95)
power2 <- c(72, 82, 78, 69, 74, 85, 89)
dt <- data.frame(speed=speed, power1=power1, power2=power2)
dt <- melt(data = dt, id.vars = c("speed"))

我正在使用以下代码制作绘图:

p <- ggplot(data = dt, aes(x = speed, y = value, fill = variable)) + 
geom_point(aes(color=variable), size = 2) +
stat_smooth(aes(color=variable), method = lm, formula = y ~ poly(x, 2), se = FALSE, size = 1)

p <- p + geom_text(aes(x = 100,
y = 93,
label = lm_eqn(lm(formula = value ~ poly(speed,2),
data = subset(x = dt, subset = variable == "power1")
)
)
),
color = "black",
parse = TRUE) +
geom_text(aes(x = 250,
y = 72,
label = lm_eqn(lm(formula = value ~ poly(speed,2),
data = subset(x = dt, subset = variable == "power2")
)
)
),
color = "black",
parse = TRUE)

p

标签的帮助函数:

lm_eqn = function(m) {
# from:
# https://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph

l <- list(a = format(coef(m)[1], digits = 2),
b = format(abs(coef(m)[2]), digits = 2),
c = format(abs(coef(m)[3]), digits = 2),
s1 = ifelse(test = coef(m)[2]>0, yes = "+", no = "-"),
s2 = ifelse(test = coef(m)[3]>0, yes = "+", no = "-"),
r2 = format(summary(m)$r.squared, digits = 3));

eq <- substitute(italic(y) == a~~s1~~b %.% italic(x)^2 ~~s2~~c%.% italic(x)*","~~italic(r)^2~"="~r2,l)

as.character(as.expression(eq));
}

剧情是这样的:

ggplot2 plot

那么,如何:
- 将 geom_text 颜色更改为与点颜色相同?
- 删除图例标题?

最佳答案

首先,只需将 color = "power1"color = "power2" 添加到相应的 geom_text() 调用中。这将设置适当的颜色,但会在您的图例中给您一个讨厌的(但预期)“a”。要删除“a”文本,请将 show_guide=FALSE 添加到每个 geom_text() 调用中。

其次,我相信您希望第一个 aes 调用具有 group = variable not fill = variable .当您尝试从图例中删除标题时,这将有助于消除混淆。要从图例中删除标题,请添加 guides(color = guide_lengend(title=NULL))

代码:

p <- ggplot(data = dt, aes(x = speed, y = value, group = variable)) + 
geom_point(aes(color=variable), size = 2) +
stat_smooth(aes(color=variable), method = lm, formula = y ~ poly(x, 2), se = FALSE, size = 1) +
geom_text(aes(x=100, y=93, label="First Label", color="power1"), show_guide=F) +
geom_text(aes(x=250, y=72, label="Second Label", color="power2"), show_guide=F) +
guides(color = guide_legend(title=NULL))
p

结果:

Result

注意:您需要小心使用 geom_text() 生成的重叠绘图 - 请参阅 post还有这个answer了解更多信息和想法。

关于r - 将 geom_text 颜色与绘图中的元素匹配并删除 ggplot2 中的图例标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27925153/

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