Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a multiple bar chart in ggplot2?

Tags:

r

ggplot2

I'm struggling a bit with ggplot2 and hoping to learn by example a bit more.

I have a lot of data that looks like like the thing this generates:

data.frame(version=c('v1', 'v1', 'v1', 'v1', 'v2', 'v2', 'v2', 'v2'),
           platform=c('linux', 'linux', 'mac', 'mac',
                      'linux', 'linux', 'mac', 'mac'),
           type=c('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'),
           count=floor(runif(8, 0, 10000)))

I got regular barplot to draw me a stacked bar chart of type for a given OS (by slicing it out with cast, but I've not quite got what I want with ggplot2 yet.

I can manage to plot a single platform by doing something like this (assuming the above is saved as sample):

qplot(version, a, data=cast(sample[sample$platform=='linux',],
                            version ~ type, value="count"),
      geom='bar')

Ideally, I'd like that stacked by type (explicitly a in this example -- there are only two types) and then have one per platform appear side-by-side on the same chart grouped by version.

That is, for every version, I'd like three bars (one for each platform) with two stacks each (by type).

like image 986
Dustin Avatar asked Aug 20 '11 20:08

Dustin


People also ask

How do I make a grouped bar chart in R?

Then the user needs to call the geom_bar() function from the ggplot package with the required parameters into it to create the grouped bar plot in the R programming language. geom_bar() function: This function makes the height of the bar proportional to the number of cases in each group.


1 Answers

Here's one option:

dat <- data.frame(version=c('v1', 'v1', 'v1', 'v1', 'v2', 'v2', 'v2', 'v2'),
           platform=c('linux', 'linux', 'mac', 'mac',
                      'linux', 'linux', 'mac', 'mac'),
           type=c('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'),
           count=floor(runif(8, 0, 10000)))


ggplot(data = dat, aes(x = platform, y = count)) + 
    facet_wrap(~version) + 
    geom_bar(aes(fill = type))

which produces something like this:

enter image description here

Your example data only had two platforms, so maybe that was just a typo since you referenced three.

like image 194
joran Avatar answered Oct 16 '22 19:10

joran