[R] how do I draw such a barplot?

hadley wickham
Tue, 17 Jul 2007 04:26:08 -0000

On 7/16/07, Donatas G. <dgvirtual at akl.lt>
wrote:
> Hi,
>
> I cannot figure out how to draw a certain plot: could someone help me out?
>
> I have this data.frame from a survey
> my.data
>
> that looks like something like this:
>
>    col1  col2  col3  col4
> 1     5     5     4     5
> 2     3     5     3     1
> 3     2     3     4     5
> 4     3     1     1     2
> 5     5     5     4     5
> 6     4     2     5     5
> ....
>
>
> Each row represents a single questionnaire with someone giving his
> agreement/disagreement with a statement (each column is a statement) that
is
> coded from 1 to 5.
>
> I need to draw a barplot giving a visual representation showing differences
> between the five columns: Each bar should represent a single column, and
> should be divided into 5 sections, the thickness of each depending on the
> number of respondents who choose that particular answer.
>
> How do I do that? All I have managed to do so far is to produce a barplot
of a
> single column, and that - only with bars side by side...

One way would be the use the ggplot2 and reshape packages:

library(ggplot2)
df <- as.data.frame(matrix(sample(1:5, 100, rep=T), ncol=5))

dfm <- melt(df, m=1:5)
qplot(variable, data=dfm, geom="bar", fill=factor(value))
qplot(variable, data=dfm, geom="bar", fill=factor(value),
position="dodge")
qplot(variable, data=dfm, geom="bar", fill=factor(value), facets = . ~
value)

Hadley