9

I want to create a bardiagram for these data in R (read from a CVS file):

Experiment_Name MetricA MetricB Just_X 2 10 Just_X_and_Y 3 20

to have the following diagram:

alt text

I am beginner and I do not know even how to start.

Stephan Kolassa
  • 95,027
  • 13
  • 197
  • 357
Skarab
  • 987
  • 4
  • 11
  • 14
  • 1
    ?barplot reading the help file is sometimes quicker than posting on a forum... – RockScience Oct 22 '10 at 10:34
  • You must first figure out that barplots are made by barplot function... this is not that easy when you don't know that. –  Oct 26 '10 at 17:24
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – kjetil b halvorsen Nov 30 '14 at 19:15

3 Answers3

13

I shall assume that you are able to import your data in R with read.table() or the short-hand read.csv() functions. Then you can apply any summary functions you want, for instance table or mean, as below:

x <- replicate(4, rnorm(100))
apply(x, 2, mean)

or

x <- replicate(2, sample(letters[1:2], 100, rep=T))
apply(x, 2, table)

The idea is to end up with a matrix or table for the summary values you want to display.

For the graphical output, look at the barplot() function with the option beside=TRUE, e.g.

barplot(matrix(c(5,3,8,9),nr=2), beside=T, 
        col=c("aquamarine3","coral"), 
        names.arg=LETTERS[1:2])
legend("topleft", c("A","B"), pch=15, 
       col=c("aquamarine3","coral"), 
       bty="n")

The space argument can be used to add an extra space between juxtaposed bars.

alt text

chl
  • 50,972
  • 18
  • 205
  • 364
13

Here ggplot version:

library(ggplot2)
df = melt(data.frame(A=c(2, 10), B=c(3, 20), 
          experiment=c("X", "X & Y")),
          variable_name="metric")

ggplot(df, aes(experiment, value, fill=metric)) + 
       geom_bar(position="dodge")

alt text

csgillespie
  • 11,849
  • 9
  • 56
  • 85
teucer
  • 1,801
  • 2
  • 16
  • 29
1

I wanted to update teucer's answer to reflect reshape2.

library(ggplot2)
library(reshape2)
df = melt(data.frame(A=c(2, 10), B=c(3, 20), 
                 experiment=c("X", "X & Y")),
      variable.name="metric")

ggplot(df, aes(experiment, value, fill=metric)) + 
  geom_bar(position="dodge",stat="identity")

Note that teucer's answer produces the error "Error in eval(expr, envir, enclos) : object 'metric' not found" with reshape2 because reshape2 uses variable.name instead of variable_name.

I also found that I needed to add stat="identity" to the geom_bar function because otherwise it gave "Error : Mapping a variable to y and also using stat="bin"."

Colin D
  • 111
  • 3