gpt4 book ai didi

r - ggplot2:如何拥有不同颜色的 geom_vline()

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

我的情节中有这五 (5) 个 geom_vline(),我希望它们具有不同的颜色。有没有办法做到这一点?

这是我的代码,

library(ggplot2)

x <- seq(-7, 8, length = 90)
tvalues <- dt(x,15)

qplot(x, tvalues) + geom_polygon(fill = "purple", colour = "purple", alpha = 0.5) +
geom_point(fill = "purple", colour = "purple", alpha = 0.2, pch = 21) +
geom_vline(xintercept = c(a <- c(-2.27685371, 0.01661155,
0.33598194, 1.92426022), mean(a)), linetype = "dashed", colour = "red") + theme_bw() + xlab(bquote(bold('Average Tensile Strength (lb/in'^'2'*')'))) +
ylab(expression(bold(P(x)))) +
opts(title = expression(bold("Student t Distribution")), plot.title = theme_text(size = 20, colour = "darkblue"),
panel.border = theme_rect(size = 2, colour = "red"))

这是输出,

enter image description here

注意图中的五条垂直线,我希望每条线都有不同的颜色,

我试过这个
library(colorRamps)
geom_vline(xintercept = c(a <- c(-2.27685371, 0.01661155,
0.33598194, 1.92426022), mean(a)), linetype = "dashed", colour = matlab.like(5))

但没用,再试一次
geom_vline(xintercept = c(a <- c(-2.27685371,  0.01661155,  
0.33598194, 1.92426022), mean(a)), linetype = "dashed", colour = c("red","blue","green","yellow","orange"))

仍然不成功。

提前致谢!

最佳答案

所以你有点错过了 背后的基本思想。 ggplot2 ,也就是说你总是把你所有的数据放到一个data.frame并且您映射的每种美学都对应于数据框中的一个变量。

您可以获得 5 条垂直线,每条线的颜色不同,并通过 5 次单独调用 geom_vline但这错过了整个包装的重点。相反,您创建一个数据框:

a <- c(-2.27685371,0.01661155,0.33598194,1.92426022)
vlines <- data.frame(xint = c(a,mean(a)),grp = letters[1:5])

我已经明确创建了一个分组变量 grp映射到 colour .然后我们使用 aes 添加图层并将美学映射到这些变量。 :
qplot(x, tvalues) + 
geom_polygon(fill = "purple", colour = "purple", alpha = 0.5) +
geom_point(fill = "purple", colour = "purple", alpha = 0.2, pch = 21) +
geom_vline(data = vlines,aes(xintercept = xint,colour = grp), linetype = "dashed") +
theme_bw() +
xlab(bquote(bold('Average Tensile Strength (lb/in'^'2'*')'))) +
ylab(expression(bold(P(x)))) +
opts(title = expression(bold("Student t Distribution")),
plot.title = theme_text(size = 20, colour = "darkblue"),
panel.border = theme_rect(size = 2, colour = "red"))

(颜色很难区分,因为它们是虚线,其中两个几乎在彼此之上。)

您将从 中获得更多 yield ggplot2 如果您从 qplot 过渡往 ggplot()并开始将您的数据放入数据框而不是向量中。

关于r - ggplot2:如何拥有不同颜色的 geom_vline(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11102129/

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