12

I would like to know how to get 9 grouping bar plot (3x3) together.

My CSV:

data <- read.csv("http://pastebin.com/raw.php?i=6pArn8GL", sep = ";")

The 9 plots should be grouped according "Type" A to I.

Then each grouped bar plot should have the frequency on the y axis, the x axis is grouped by 1 pce to 6 pce and subdivided by year.

I have the following example on Excel (cf. image) and would like to create the same result on r with ggplot. Is it possible?

enter image description here

tdy
  • 36,675
  • 19
  • 86
  • 83
S12000
  • 3,345
  • 12
  • 35
  • 51

2 Answers2

31

First, reshape your data from wide to long format.

library(reshape2)
df.long<-melt(df,id.vars=c("ID","Type","Annee"))

Next, as during importing data letter X is added to variable names starting with number, remove it with substring().

df.long$variable<-substring(df.long$variable,2)

Now use variable as x, value as y, Annee for fill and geom_bar() to get barplot. With facet_wrap() you can split data by Type.

ggplot(df.long,aes(variable,value,fill=as.factor(Annee)))+
   geom_bar(position="dodge",stat="identity")+
   facet_wrap(~Type,nrow=3)

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • 1
    Hello thanks is impressive but on my side I get an error message saying Error in layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting – S12000 Jun 25 '13 at 18:03
  • @Swiss12000 Are you using the code exactly the same way as my code? If not please add the code you use in your question. – Didzis Elferts Jun 25 '13 at 18:08
  • indeed I need a mistake is perfectely working thanks for your help. I have the R Graphics Cookbook to learn ggplot but they don't mention how to do more complex graph. Did you learn ggplot everyday a bit or did you read an advanced books? – S12000 Jun 25 '13 at 18:13
  • 2
    @Swiss12000 I learned by doing and by reading and answering questions here on SO – Didzis Elferts Jun 25 '13 at 18:15
  • 1
    I found useful this documentation about melt: http://www.cookbook-r.com/Manipulating_data/Converting_data_between_wide_and_long_format/ – GermanK Mar 27 '15 at 19:23
  • tidyr version please ? – Mostafa90 Mar 16 '16 at 13:38
10

Using @Didzis reshaped data , here a lattice version:

barchart(value~variable|Type,
         groups=Annee,data=df.long,layout=c(3,3),
         between=list(3,3),
         axis=axis.grid,
         auto.key=TRUE)

enter image description here

agstudy
  • 119,832
  • 17
  • 199
  • 261