在图ggplot中添加垂直线

时间:2013-10-27 18:55:07

标签: r ggplot2

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

library (ggplot2)

png (filename = "graph.png")
stats <- read.table("processed-r.dat", header=T, sep=",")
attach (stats)
stats <- stats[order(best), ]
sp <- stats$A / stats$B
index <- seq (1, sum (sp >= 1.0))
stats <- data.frame (x=index, y=sp[sp>=1.0])
ggplot (data=stats, aes (x=x, y=y, group=1)) + geom_line()
dev.off ()

enter image description here

1 - 如何在图中添加垂直线与y的特定值相交(例如2)?

2 - 如何使y轴从0.5开始而不是1?

2 个答案:

答案 0 :(得分:64)

您可以使用geom_vline()添加垂直线。在你的情况下:

+ geom_vline(xintercept=2)

如果您想在y轴上看到数字0.5,请添加scale_y_continuous()并设置limits=breaks=

+ scale_y_continuous(breaks=c(0.5,1,2,3,4,5),limits=c(0.5,6))

答案 1 :(得分:20)

关于第一个问题:

这个答案假设你想要的Y值特别在你的数据集中。首先,让我们创建一个可重现的示例,因为我无法访问您的数据集:

set.seed(9999)
stats <- data.frame(y = sort(rbeta(250, 1, 10)*10 ,decreasing = TRUE), x = 1:250)
ggplot(data=stats, aes (x=x, y=y, group=1)) + geom_line()

initial plot

您需要做的是使用数据框中的y列来搜索特定值。基本上你需要使用

ggplot(data=stats, aes (x=x, y=y, group=1)) + geom_line() + 
    geom_vline(xintercept = stats[stats$y == 2, "x"])

使用我在上面生成的数据,这是一个例子。由于我的数据框可能不包含确切的值2,因此我将使用trunc函数来搜索它:

stats[trunc(stats$y) == 2, ]

#           y  x
# 9  2.972736  9
# 10 2.941141 10
# 11 2.865942 11
# 12 2.746600 12
# 13 2.741729 13
# 14 2.693501 14
# 15 2.680031 15
# 16 2.648504 16
# 17 2.417008 17
# 18 2.404882 18
# 19 2.370218 19
# 20 2.336434 20
# 21 2.303528 21
# 22 2.301500 22
# 23 2.272696 23
# 24 2.191114 24
# 25 2.136638 25
# 26 2.067315 26

现在我们知道2的所有值都在哪里。由于此图表正在减少,我们将反转它,然后最接近2的值将在开头:

rev(stats[trunc(stats$y) == 2, 1])

#           y  x
# 26 2.067315 26

我们可以使用该值来指定x截距应该在哪里:

ggplot(data=stats, aes (x=x, y=y, group=1)) + geom_line() + 
    geom_vline(xintercept = rev(stats[trunc(stats$y) == 2, "x"])[1])

plot with vertical line

希望有所帮助!

相关问题