我正在努力研究如何real_values在估計值旁邊繪制我的真實值,呈現在向量中。我的問題是估計值有一個范圍(通過geom_errorbar),對于實際值,我只想在 10 個估計值的每個左側繪制黑色點。
這是我嘗試過的一個例子:
est_values = rnorm(20)
real_values = rnorm(10)
dat_ex = data.frame(
xvalues = 1:10,
values = est_values,
method = c(rep("A",10),rep("B",10)),
ic_0.025 = c(est_values - rnorm(20,1,0.1)),
ic_0.975 = c(est_values rnorm(20,1,0.1)))
ggplot(dat_ex)
#geom_point(aes(x = 1:10, y= real_values), size = 2)
geom_point(aes(x = xvalues, y= values, group = method, colour = method), position=position_dodge(.9), size = 3)
geom_errorbar(aes(x = xvalues, y= values, group = method, colour = method,ymin = ic_0.025, ymax = ic_0.975), size = 1.3,position=position_dodge(.9), width = .2)

uj5u.com熱心網友回復:
ggplot通常最適用于資料框中的資料。因此,我們將您real_values放入一個資料框中并將它們繪制在一個單獨的層中,并根據要求將它們“輕推”到左側:
ggplot(dat_ex)
geom_point(aes(x = xvalues, y= values, group = method, colour = method), position=position_dodge(.9), size = 3)
geom_errorbar(aes(x = xvalues, y= values, group = method, colour = method,ymin = ic_0.025, ymax = ic_0.975), size = 1.3,position=position_dodge(.9), width = .2)
geom_point(
data = data.frame(values = real_values, xvalues = dat_ex$xvalues),
aes(x = xvalues, y = values),
position = position_nudge(x = -.4),
color = "black")

更好的方法可能是將它們全部放在同一個資料框中。這可以簡化代碼并自動將它們放入圖例中。
library(dplyr)
dat_ex = data.frame(
xvalues = 1:10,
values = real_values,
method = "real"
) %>%
bind_rows(dat_ex) %>%
mutate(method = factor(method, levels = c("real", "A", "B")))
ggplot(dat_ex, aes(x = xvalues, y = values, color = method))
geom_point(position=position_dodge(.9), size = 3)
geom_errorbar(aes(ymin = ic_0.025, ymax = ic_0.975, group = method),
size = 1.3, position=position_dodge(.9), width = .2)
scale_color_manual(values = c("real" = "black", "A" = "orange", "B" = "blue"))

uj5u.com熱心網友回復:
我會將real_values您的資料添加為另一個級別method,因此它們將與“A”和“B”一起被躲避(并包含在圖例中):
library(ggplot2)
dat_ex <- rbind(
dat_ex,
data.frame(
xvalues = 1:10,
values = real_values,
method = "Real",
ic_0.025 = NA_real_,
ic_0.975 = NA_real_
)
)
# arrange so "Real" is on the left
dat_ex$method <- factor(dat_ex$method, levels = c("Real", "A", "B"))
ggplot(dat_ex)
geom_point(aes(x = xvalues, y= values, group = method, colour = method), position=position_dodge(.9), size = 3)
geom_errorbar(aes(x = xvalues, y= values, group = method, colour = method,ymin = ic_0.025, ymax = ic_0.975), size = 1.3,position=position_dodge(.9), width = .2)
scale_colour_manual(values = c("black", "forestgreen", "royalblue"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435710.html
上一篇:ggplot按多列分組
下一篇:在分組條形圖上方添加計數和百分比
