[英]How to overlay means and error bars with jitter dots and smooth distribution with ggplot2 in R?
[英]How to draw means and error bars on axes in ggplot2 R
我想在R中的qplot的軸上繪制平均值和誤差線。這里我提供了一個我的意思的例子:
正如您在黃色軸上看到的那樣是繪制平均值和誤差線。 我想在我的qplot上有這個。
考慮這個數據子集:
x <- c(2.037820, 3.247560, 1.259053, 4.200520, 1.960179, 6.247880, 2.830693, 5.565390, 4.476610,
4.627420, 2.500470, 4.156422, 2.855426, 9.210740, 2.663490, 4.412452, 3.270280, 2.838081,
1.705650, 5.440690, 3.014000, 3.513820, 3.002930, 2.453080, 2.787320, 0.979227, 2.815368);
y <- c(2.855820, 3.332350, 1.991730, 3.688240, 3.565680, 3.525511, 4.451860, 3.233950, 6.125230,
4.039360, 5.043330, 3.194650, 7.419020, 7.389600, 2.734740, 4.456250, 3.037665, 5.147140,
3.184790, 3.595890, 5.457550, 1.527680, 2.848046, 1.418289, 3.996330, 4.516640, 2.884100);
fp <- qplot(x, y) + annotate("segment", x=-Inf, xend=Inf,y=-Inf, yend=Inf);
ggExtra::ggMarginal(fp, type = "density", margins = 'both')
它應該給你一個這樣的情節:
現在,我如何繪制我的手段和錯誤欄? R中基本圖中使用的軸()在ggplot2中不起作用。
我感謝任何建議,即使它需要更改包或以不同方式處理問題。
謝謝!
也許不完全是您正在尋找的東西,但可能是您繼續努力的起點:
require(ggplot2)
require(dplyr)
df <- data.frame(x = x, y = y)
dferrx <- df %>%
summarise(m = mean(x),
lo = m - 1.96 * sd(x)/sqrt(n()),
hi = m + 1.96 * sd(x)/sqrt(n()),
x = m)
dferry <- df %>%
summarise(m = mean(y),
lo = m - 1.96 * sd(y)/sqrt(n()),
hi = m + 1.96 * sd(y)/sqrt(n()),
y = m)
ggplot(df, aes(x = x, y = y)) +
geom_point() +
annotate("segment", x=-Inf, xend=Inf,y=-Inf, yend=Inf) +
geom_errorbar(data = dferry, aes(x = 0, ymin = lo, ymax = hi)) +
geom_errorbarh(data = dferrx, aes(y = 0, xmin = lo, xmax = hi))
你可能已經解決了它,但是,以防萬一,這里是每個點的錯誤欄的代碼,遵循Wietze314的貢獻:
library(tidyverse)
example_DF <- tibble(x = c(2.037820, 3.247560, 1.259053, 4.200520, 1.960179, 6.247880, 2.830693, 5.565390, 4.476610,
4.627420, 2.500470, 4.156422, 2.855426, 9.210740, 2.663490, 4.412452, 3.270280, 2.838081,
1.705650, 5.440690, 3.014000, 3.513820, 3.002930, 2.453080, 2.787320, 0.979227, 2.815368),
y = c(2.855820, 3.332350, 1.991730, 3.688240, 3.565680, 3.525511, 4.451860, 3.233950, 6.125230,
4.039360, 5.043330, 3.194650, 7.419020, 7.389600, 2.734740, 4.456250, 3.037665, 5.147140,
3.184790, 3.595890, 5.457550, 1.527680, 2.848046, 1.418289, 3.996330, 4.516640, 2.884100))
dferrx <- example_DF %>%
summarise(m = mean(x),
lo = m - 1.96 * sd(x)/sqrt(n()),
hi = m + 1.96 * sd(x)/sqrt(n()),
x = m)
dferry <- example_DF %>%
summarise(m = mean(y),
lo = m - 1.96 * sd(y)/sqrt(n()),
hi = m + 1.96 * sd(y)/sqrt(n()),
y = m)
ggplot(example_DF, aes(x = x, y = y)) +
geom_point() +
annotate("segment", x=-Inf, xend=Inf,y=-Inf, yend=Inf) +
geom_errorbar(aes(ymin =y -dferry$lo, ymax = y+ dferry$hi))+
geom_errorbarh(aes(xmin =x -dferrx$lo, xmax = x+ dferrx$hi))
它會從很多美學修補中受益,但它確實存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.