使用构面时,如何将值向量传递给geom_vline?

时间:2019-06-19 18:41:13

标签: r ggplot2

我有一个包含几列的数据框,每一列对应一个不同的ID。我使用以下代码为每列创建了一个密度图:

 ggplot(melt(df),aes(x=value)) + geom_density() + 
 facet_wrap_paginate(~variable, nrow = 3, ncol = 2, page = 1, scales = 
 "free") 

我想做的是在每个图上添加一条垂直线,该垂直线对应于向量中的特定值。例如,我想绘制一条垂直线,其x截距对应于第一个构面/图的矢量中的第一个值,以此类推,绘制第二个,第三个...

我尝试过:

 ggplot(melt(df),aes(x=value)) + geom_density() + 
 geom_vline(aes(yintercept = vector))
 facet_wrap_paginate(~variable, nrow = 3, ncol = 2, page = 1, scales = 
 "free") 

但这不起作用。任何帮助,将不胜感激!谢谢!

以下是数据示例:

structure(list(P1 = c(2.020089156, 1.146085334, -1.419562976, 
1.291621209, -1.288234235, 0.596079171, -0.114523205, 0.318296715, 
-0.710111131, 1.234172157, 1.638215841, 0.074228733, -0.418031048, 
-0.873318667, -1.099210823, 1.055800864, -0.258843912, -1.299183683, 
1.679751351, -0.332529691), P2 = c(-0.200656757, -0.905949115, 
-0.123085761, 1.564677289, -0.289882157, -0.162469608, 1.208284733, 
0.079959849, -0.212177202, 1.375590172, 0.872137796, -0.253766902, 
-0.861501631, -0.370784258, -0.463778362, 0.358558145, 1.017652625, 
-0.753227309, 3.385005831, -0.421509939), P3 = c(-0.733666761, 
-0.107249708, 1.051832738, -0.308113556, -0.08050586, 0.503093678, 
0.293885202, 0.765470656, -0.250293951, 0.173549289, 1.611834764, 
0.380911004, -0.843674488, 0.660706821, -0.189601606, 0.502569289, 
-0.580795921, -0.412284603, 1.629367602, -0.397373712), P4 = c(0.77604806, 
-0.06368464, 0.16445295, 0.45655382, -1.29685072, -0.54675214, 
-0.23219627, -0.47352554, -0.04939622, -0.75526638, 0.87428248, 
-1.71997627, 0.06243265, 0.95946773, 1.04786879, 0.53349193, 
-0.6434623, -0.81765584, -0.35355488, -1.74251801), P5 = c(-0.833394003, 
1.225244117, -0.70948569, -0.004266946, -0.272899255, 0.654305811, 
-0.274527936, 0.106797649, 0.11825556, 0.670149731, 0.825460151, 
0.089353621, -0.22925347, 0.796101039, 1.035388522, 0.815188034, 
-0.955502196, -0.374220339, -0.491128182, 0.965498118), P6 = c(-0.52589579, 
1.02997904, 1.16576282, 0.46506523, -0.2265231, -0.16677585, 
0.12376603, 1.36208941, -1.67231104, 1.02273936, 0.42407352, 
0.67183367, 0.04955931, -0.41284541, -0.50013924, 1.05752563, 
-0.29500172, -0.53794867, 2.27617856, -0.56288976)), row.names = c(NA, 
20L), class = "data.frame")

我要添加的值的向量为:

refvals <- c(0.23, -0.1, 0.5, 0.88, -0.31, -0.38)

1 个答案:

答案 0 :(得分:1)

您需要创建一个data.frame,其中包含用于构面的变量:

@p

enter image description here