0
votes

bargraph from sciplot allows us to plot bar chart with error bars. It also allows grouping by independent variables (factors). I want to group by dependent variable, how can I achieve that

bargraph.CI(x.factor, response, group=NULL, split=FALSE,
col=NULL, angle=NULL, density=NULL,
lc=TRUE, uc=TRUE, legend=FALSE, ncol=1,
leg.lab=NULL, x.leg=NULL, y.leg=NULL, cex.leg=1,
bty="n", bg="white", space=if(split) c(-1,1),
err.width=if(length(levels(as.factor(x.factor)))>10) 0 else .1,
err.col="black", err.lty=1,
fun = function(x) mean(x, na.rm=TRUE),
ci.fun= function(x) c(fun(x)-se(x), fun(x)+se(x)),
ylim=NULL, xpd=FALSE, data=NULL, subset=NULL, ...)

The specification of bargraph.CI is shown above. The response variable is usually numerical vector. This time, I really want to plot three response variables (A,B,C) against the same independent variables. Let me use the data frame "mpg" to illustrate the problem. I can sucessufully get a plot with the following code, here the DV is hwy

data(mpg)
attach(mpg)

bargraph.CI(
class,  #categorical factor for the x-axis
hwy,    #numerical DV for the y-axis
group=NULL,   #grouping factor
legend=T, 
ylab="Highway MPG",
xlab="Class")

I can also successfully get a plot with the only change being the DV (changed from hwy to cty)

data(mpg)
attach(mpg)

bargraph.CI(
class,  #categorical factor for the x-axis
cty,    #numerical DV for the y-axis
group=NULL,   #grouping factor
legend=T, 
ylab="Highway MPG",
xlab="Class")

However, if I want to use the two DVs at the same time, I mean, for each group, I want to display two bars, one for cty and one for hwy.

data(mpg)
attach(mpg)

bargraph.CI(
class,  #categorical factor for the x-axis
c(cty,hwy),    #numerical DV for the y-axis
group=NULL,   #grouping factor
legend=T, 
ylab="Highway MPG",
xlab="Class")

it won't work because of mismatched dimension. How can I achieve this? Well, actually similar effect of bargraph can be achieved by using the method from Boxplot schmoxplot: How to plot means and standard errors conditioned by a factor in R? with ggplot2. So if you have any idea of how to do it with ggplot2, it's also fine for me.

1

1 Answers

0
votes

As happens often when displaying data, you should manipulate the data first and then use bargraph.CI. In your expamle, the data.frame that you would like to visualize is the following:

df <- data.frame(class=c(mpg$class, mpg$class), 
                 value=c(mpg$cty, mpg$hwy), 
                 grp=rep(c("cty", "hwy"), each=nrow(mpg)))

Then you can use bargraph.CI on this new data.frame.

bargraph.CI(
  class,        #categorical factor for the x-axis
  value,        #numerical DV for the y-axis
  group=grp,    #grouping factor
  data=df, 
  legend=T, 
  ylab="Highway MPG",
  xlab="Class")