【问题标题】:Adding vertical line in plot ggplot在绘图ggplot中添加垂直线
【发布时间】:2013-10-27 18:55:07
【问题描述】:

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

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 ()

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

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用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))
    

    【讨论】:

    • 似乎 OP 想要在“y 的特定值”处绘制垂直线。干杯。
    • @Henrik 是的,你是对的,我误解了这个问题,但 ZNK 已经给出了这个问题的答案
    【解决方案2】:

    关于第一个问题:

    这个答案是假设你想要的 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()
    

    您需要做的是使用数据框中的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])
    

    希望有帮助!

    【讨论】: