我的情节中有五(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"))
这是输出,
注意图中的五条垂直线,我希望每条线都有不同的颜色,
我试过这个
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"))
仍然不成功。
提前致谢!
答案 0 :(得分:28)
所以你有点想念 ggplot2 背后的基本理念,那就是你总是将所有数据都放到data.frame
中,并且你绘制的每个美学对应一个变量你的数据框。
您可以获得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"))
(颜色很难区分,因为它们是虚线,其中两个几乎相互叠加。)
如果您从qplot
过渡到ggplot()
并开始将数据放入数据框而不是矢量,您将从 ggplot2 中获得更多。
答案 1 :(得分:5)
如果您只想添加一行,添加以下geom
会在x=1
处添加红色的垂直线并以虚线显示。
+ geom_vline(aes(xintercept=1), colour="#BB0000", linetype="dashed")