0

I'd like to do the following in R.

I have a group of individuals (1 - 50) with two datasets each. Each dataset (A & B) has values that can be in two categories (Gains, shown in blue; Losses, shown in red). I'd like to show those two datasets together, as below. The frequency of Gains/Losses would be in the y axis, where Dataset A would go upward from the x axis, and Dataset B would go downward from the x axis. I'd like to be able to cluster the barplot either by Individual (as shown below) OR by Gains or Losses (All gains together, then all losses together).

I know how to make clustered barplots in ggplot, but can't figure out how to combine the two datasets as in my image (with dataset A going up and dataset B going down).

An image of what I want

Gaius Augustus
  • 940
  • 2
  • 15
  • 37

1 Answers1

1

We can do something similar to age pyramids, only without flipping the coordinates

testA <- data.frame(v=as.factor(sample(1:2,1000,replace=T, prob = c(1,5))), dataset='A')
testB <- data.frame(v=as.factor(sample(1:2,1000,replace=T, prob = c(5,1))), dataset='B')

require(ggplot2)
require(plyr)    
ggplot(data=rbind(testA, testB),aes(x=as.factor(v),fill=v)) + 
    geom_bar(subset=.(dataset=="A")) + 
    geom_bar(subset=.(dataset=="B"),aes(y=..count..*(-1))) 

barplot

Community
  • 1
  • 1
Neal Fultz
  • 9,282
  • 1
  • 39
  • 60