简体   繁体   中英

How to plot Two Sample t.test() means, medians, and CI in R?

With the data I have, this R code x <- t.test(Age ~ Completers, var.equal = TRUE, data = data) renders the following result:

    Two Sample t-test

data:  Age by Completers
t = 0.93312, df = 1060, p-value = 0.351
alternative hypothesis: true difference in means between group Completers and group Non Completers is not equal to 0
95 percent confidence interval:
 -0.5844018  1.6442118
sample estimates:
    mean in group Completers mean in group Non Completers
                    37.16052                     36.63062

What I would like is to plot each mean (found in x$estimate[1] and x$estimate[2] ) with its own point on the x axis at its proper height on the y axis (on the same graph) and each point complemented with the same confidence interval (CI) (found in x$conf.int[1] and x$conf.int[2] ). Like this[*]:

在此处输入图像描述

Unfortunately, if I'm not mistaken, plot() (from the Generic XY Plotting ) does not seem to handle this. So I tried with plotCI (from gplots ) as follows:

library(gplots)

plotCI(x = x$estimate[1], y = x$estimate[2], 
       li = x$conf.int[1], ui = x$conf.int[2])

But it renders as shown below:

在此处输入图像描述

My questions:

  • Is there a way to obtain a plot such as in the first graph with Base R code?
  • If not, what would be the solution (short of using the jmv:: code (see [*]))?

[*] Graph obtained with Jamovi Version 2.3.15.0 which uses the following code (but I would like to avoid using jmv:: ):

jmv::ttestIS(
  formula = Age ~ Completers,
  data = data,
  plots = TRUE
)

System used:

  • R 4.2.1
  • RStudio 2022.07.1 Build 554
  • macOS Monterey Version 12.5.1 (Intel)

The following should do what you want, though I dont have the data so may need a bit of tweaking:

Sample data

df <- data.frame(type = c("Completers","Non Completers"), 
                          point_est = c(37.2, 36.8),
                          ci_lo = c(36.4, 36.0),
                          ci_hi = c(38.0, 37.5))

Plot

plot(NA, xlim = c(0,3), ylim = c(35, 38), # blank plot
     axes = FALSE, xlab = "", ylab = "")
segments(x0 = c(1,2), y0 = df$ci_lo, y1 = df$ci_hi) # add segments
points(df$point_est, pch = 19) # add means
axis(1, at = 0:3, labels = c(NA, df$type, NA)) # add x axis
axis(2) #add y axis
mtext(side = 1, "Completers", padj = 4) # add x label 
mtext(side = 2, "Age", padj = -4) # add y label

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM