[R] ggplot2 stacked bar - sum of values rather than count

J Toll jctoll at gmail.com
Mon Jan 16 04:38:01 CET 2012


On Sun, Jan 15, 2012 at 9:15 PM, Richard M. Heiberger <rmh at temple.edu> wrote:
> This is based on lattice, not ggplot, and I hope I understand what you are
> trying to do.
>
> require(lattice)
>
> x <- read.table(text="
>         Value Bar Segment
>  1.10020075   1       1
> -1.37734577   2       1
>  2.50702876   3       1
>  0.58737028   3       2
>  0.21106851   3       3
> -2.50119261   4       1
>  1.34984831   5       1
> -0.27556149   6       1
> -1.54401647   6       2
> -2.75975562   6       3
> -0.09527123   6       4
>  1.36331646   7       1
> -0.36051429   8       1
>  1.36790999   9       1
>  0.15064633   9       2
>  0.34022421   9       3
> -0.64512970  10       1
>  0.83268199  11       1
> -1.50117728  12       1
>  1.09004959  13       1
> ", header=TRUE)
>
> qplot(factor(Bar), data = x, geom = "bar", fill = factor(Segment))
>
> xx <- matrix(0, 13, 4,
>              dimnames=list(1:13, 1:4))
> for (i in 1:nrow(x)) xx[x$Bar[i], x$Segment[i]] <- x$Value[i]
> xx
> barchart(xx, horizontal=FALSE)
>
>
> Please see the plot.likert function in the HH package
>
> ## install.packages("HH") ## if necessary
> library(HH)
> ?likert
>
> for a development of graphs for data similar to what you have.
>
> Rich

Rich,

Thank you for your suggestion. Your first example using the lattice
package is exactly what I was trying to do.  I will have to explore
lattice, as well as look into the HH package.

Thank you.

James








>
> On Sun, Jan 15, 2012 at 9:08 PM, J Toll <jctoll at gmail.com> wrote:
>>
>> Hi,
>>
>> I'm trying to create a stacked bar plot using ggplot2. Rather than
>> plotting the count of each of the 13 "Bar" factors on the Y axis, I
>> would like to represent the sum of the Values associated with each of
>> the 13 "Bar" factors. Is there a way to do that?  Given the following
>> data, that would obviously mean that there would be some negative sums
>> represented.  Here's a bit of example data along with the command I've
>> been using.
>>
>> >library(ggplot2)
>> > x
>>         Value Bar Segment
>> 1   1.10020075   1       1
>> 2 -1.37734577   2       1
>> 3   2.50702876 3       1
>> 4 0.58737028   3       2
>> 5   0.21106851   3       3
>> 6  -2.50119261   4       1
>> 7 1.34984831   5       1
>> 8 -0.27556149   6       1
>> 9 -1.54401647   6       2
>> 10 -2.75975562   6       3
>> 11 -0.09527123   6       4
>> 12 1.36331646   7       1
>> 13 -0.36051429   8       1
>> 14 1.36790999   9       1
>> 15 0.15064633   9       2
>> 16 0.34022421   9       3
>> 17 -0.64512970  10       1
>> 18 0.83268199  11       1
>> 19 -1.50117728  12       1
>> 20  1.09004959  13       1
>> > qplot(factor(Bar), data = x, geom = "bar", fill = factor(Segment))
>>
>> Thanks for any suggestions you might have.
>>
>> James


More information about the R-help mailing list