Skip to content
Prev 373081 / 398498 Next

barplot that displays sums of values of 2 y colums grouped by different variables

It is not generally advisable to get too fancy with stat functions in 
ggplot... things can easily get more complicated than ggplot is ready to 
handle when it comes to calculations. It is better to create data that 
corresponds directly to the graphical representations you are mapping 
them to.

Read [1] for more on this philosophy.

[1] H. Wickham, Tidy Data, Journal of Statistical Software, vol. 59, no. 
10, pp. 123, Sep. 2014. http://www.jstatsoft.org/v59/i10/

#---
library(ggplot2) # ggplot
library(dplyr)   # `%>%`, group_by, summarise
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
library(tidyr)   # gather

dta <- read.table( text =
"city n y
mon 100 200
tor 209 300
edm 98 87
mon 20 76
tor 50 96
edm 62 27
", header = TRUE )

dta2 <- (   dta
         %>% group_by( city )
         %>% summarise( n = sum( n )
                      , y = sum( y )
                      )
         %>% gather( Response, value, -city )
         )

ggplot( dta2, aes( x=city, y=value, fill = Response ) ) +
     geom_bar( stat="identity", position="dodge" )

#' ![](https://i.imgur.com/cosFf3B.png)
#---
On Mon, 15 Jan 2018, kenneth dyson wrote:

            
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k