2

I want to know if it's feasible to create a bar chart with groupings by type in ggplot the same way I would in excel. I have the following data:

 df <- data.frame(label = c("A", "A", "B", "C"), variable = c("alpha", "beta", "tim", "tom"), values = c(1,2,4,1))

In excel, I can easily create a graph that looks like this:

enter image description here

Is there a way to do something similar in ggplot, where the column 'label' groups the variables?

TuringMachin
  • 391
  • 1
  • 4
  • 10
  • Not sure if you are looking for only exactly the same kind of plot. In ggplot2, you could also do `ggplot(df, aes(x = variable, y = values, fill = label)) + geom_bar(stat = "identity")` which would fill the bars with colors according to their labels and put the color codes in a legend at the right. – talat Nov 10 '14 at 22:21
  • Yeah, that won't work for me because I actually have like 50 variables, and I don't want to have to read off the legend. – TuringMachin Nov 10 '14 at 22:23
  • Ok, I see. It seems that the answer by @jed might be just what you're after then. – talat Nov 10 '14 at 22:24
  • possible duplicate of [ggplot2 - labels of grouping values below the plot](http://stackoverflow.com/questions/18165863/ggplot2-labels-of-grouping-values-below-the-plot) – Henrik Nov 10 '14 at 22:26

1 Answers1

1

You can use facet_grid and set the scales = "free_x" and space = "free".

ggplot(df, aes(variable, values)) + geom_bar(stat = "identity") + facet_grid(~ label, scales = "free_x", space = "free")

enter image description here

jed
  • 615
  • 3
  • 11