user4021557
user4021557

Reputation:

How to use ggplot2 in R when the data is a function of tapply

I have a variable that is a function of tapply

meanx <- with(dat2, tapply(x, list(type,status), mean)) The out put reads as follows :

        Status 1 Status2
Type 1 11.99     9.8 
Type 2 88.8      100

I also have confidence intervals for the 4 means

xCI <- c(meanx - qnorm(0.975, mean=0, sd=1)*serrorx,
         meanx + qnorm(0.975, mean=0, sd=1)*serrorx)

I want to plot a simple gglpot2 barplot, with the confidence intervals. Since the meanx is a tapply function, I get stuck every time I try to use it. Its very tedious to save it as a new variable with a string of values and use it either in the normal barplot or ggplot2. Any help will be appreciated. (I am a newbie at gglopt2)

Thanks!

Upvotes: 2

Views: 1724

Answers (1)

Rorschach
Rorschach

Reputation: 32426

One possibility is converting your table output to a data.frame, and passing that to ggplot. An alternative that may be simpler would be to use the stat_summary function to compute the summary statistics in the ggplot framework.

## Sample data
dat2 <- data.frame(
  type=paste("Type ", sample(1:2, 50, TRUE)), 
  status=paste("Status ", sample(1:2, 50, TRUE)),
  x = runif(50)
)

library(ggplot2)
ggplot(dat2, aes(interaction(type, status, sep = "/"), x)) +
  stat_summary(geom="bar", fun.y=mean, fill="lightblue") +
  stat_summary(geom="errorbar", fun.data=mean_cl_boot, color="red", width=0.4) +
  theme_bw() +
  scale_x_discrete("type-status")

enter image description here

Upvotes: 2

Related Questions