[R] ggplot2 stacked bar - sum of values rather than count
J Toll
jctoll at gmail.com
Tue Jan 17 17:49:06 CET 2012
On Mon, Jan 16, 2012 at 1:13 AM, Paul <paul at paulhurley.co.uk> wrote:
> On 16/01/12 02:08, J Toll 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
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> I'm not at my usual computer, but in ggplot2 the geom_bar geom is
> designed for stats, so by default does report count. You can change the
> stat method (ie to identity to just use the values in the column) but
> the easiest (IIRC) is to give a weight;
>
> #Gives count
> ||
>
> qplot <http://had.co.nz/ggplot2/qplot.html>(color, data=diamonds, geom="bar")
>
> #Gives sum of carat variable
> qplot <http://had.co.nz/ggplot2/qplot.html>(color, data=diamonds, geom="bar", weight=carat, ylab="carat")
>
> #just gives raw values from meanprice column
> ||
>
> qplot <http://had.co.nz/ggplot2/qplot.html>(cut, meanprice, geom="bar", stat="identity")
>
> Check out the ggplot2 help page (http://had.co.nz/ggplot2/geom_bar.html) for more info.
>
> Regards,
>
> Paul.
>
Paul,
Thank you for the help. Using your second example, I added "weight =
Value" to my previous command to get the chart I wanted.
qplot(factor(Bar), data=x, geom="bar", weight = Value, fill=factor(Segment))
ggplot2 issues a warning message with my data because it has negative values:
"Warning message:
Stacking not well defined when ymin != 0 "
But that's not a real concern.
Anyway, thanks again for your help.
James
More information about the R-help
mailing list