1

I'm quite new to R studio, so I apologise in advance. I need help to create a grouped barplot. I have three variables: "Time": converted to a continuous variable "Treatment": "Con", "Hya" "Trial": "T1", "T2", "T3" I want to produce something like this:

There should be three groups of three columns stacked beside each other. Time on the Y-axis; Trial (1,2 & 3)on the X-axis; Treatment corresponding to coloured columns (Hya=grey, Con=white) with a legend explaining Treatment colour.

Here is the structure of my data:

'data.frame':   102 obs. of  3 variables:
 $ Trial    : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Treatment: $ Trial    : int  1 1 1 1 1 1 1 1 1 1 ...
 $ Treatment: Factor w/ 2 levels "Control","Hyaluronan": 1 1 1 1 1 1 1 1 1 1 ...
 $ Time     : num  11 7 7.68 7.7 7 3 5 5.48 4 6 ...

I get this error message:

> barplot(table(Biopsy$Time, Biopsy$Treatment, Biopsy$Trial))
Error in barplot.default(table(Biopsy$Time, Biopsy$Treatment, Biopsy$Trial)) : 
  'height' must be a vector or a matrix

Please if anyone is able to help I would so appreciate it, I've been trying for so long :(

Harald Gliebe
  • 7,236
  • 3
  • 33
  • 38

1 Answers1

1

I think it is useful to mention the "ggplot2" package here. With this package the creation of a stacked bar plot is quite easy. I was not sure about the data frame you are working with since you are only providing a snapshot of your data structure, but I hope the data frame I created as an example will help to show you the basic function used to create such a plot. (You can just copy-paste in RStudio and run the code. Make sure to install the ggplot2 [install.packages("ggplot2")] package before running the library() function.)

trial <- c(1,1,1,1,2,2,2,2,3,3,3,3)
treatment <- c("Hya","Hya","Con","Con","Hya","Hya","Con","Con","Hya","Hya","Con","Con")
time <- c(1,7,1,7,2,8,2,8,3,9,3,9)

df <- data.frame(trial,treatment,time)

library(ggplot2)
ggplot(df, aes(y = time,
               x = trial,
               group = treatment)) +
  geom_bar(stat = "identity", position = "dodge", aes(fill = treatment))

The resulting plot can be found here.

The above code will create a data frame and a bar plot. The grouping is done with the argument "group", the color set with "fill". Of course you can modify the coloring etc. Since you are new RStudio/R I recommend you check out the documentation of ggplot.

I hope this example helps...

CPak
  • 13,260
  • 3
  • 30
  • 48
Ben
  • 99
  • 6