[R] Some problems with back to back bar plots in ggplot2

Gavin Rudge g.rudge at bham.ac.uk
Wed Jul 17 12:58:39 CEST 2013


Hi, I'm making a simple population pyramid using two back-to-back bar plots for 18 different age groups with totals for males and females.

Yesterday I achieved a fairly serviceable plot using the following.

library(ggplot2)
library(reshape2)
library(plyr)
#make sample data
df<-data.frame(ag=c(1:18),males=sample(100:200,18),females=sample(100:200,18))
#melted as per original data set
df<-melt(df,id="ag")
df
#my plot
ggplot(data=df,aes(x=ag))+geom_bar(subset=.(variable=="males"),aes(y=value),stat="identity",fill="#330099")+
  geom_bar(subset=.(variable=="females"),aes(y=-value),stat="identity",fill="#FF9333")+
  scale_y_continuous(breaks=seq(-200,200,50),labels=abs(seq(-200,200,50)))+
  scale_x_continuous(breaks=seq(1,18,1),labels=abs(seq(1,18,1)))+coord_flip()+
  theme_bw()+xlab("age group")+ylab("population")

Today it threw errors. I updated to R studio 0.97.551.  I also made sure I had the latest R 3.0.1, and reinstalled the packages I was using. This is all running on Windows 7.

It still threw errors. So I tried specifying all of the variables with their full names, which got me a plot.

ggplot(data=df,aes(x=df$ag))+geom_bar(subset=.(df$variable=="males"),aes(y=df$value),stat="identity",fill="#330099")+
  geom_bar(subset=.(df$variable=="females"),aes(y=-df$value),stat="identity",fill="#FF9333")+
  scale_y_continuous(breaks=seq(-200,200,50),labels=abs(seq(-200,200,50)))+
  scale_x_continuous(breaks=seq(1,18,1),labels=abs(seq(1,18,1)))+coord_flip()+
  theme_bw()+xlab("age group")+ylab("population")

But now my y axis (which in my case is horizontal as I flipped the co-ords) won't scale properly.  From what I recall, it looked fine yesterday.

I'm trying to get back to a properly scaled population pyramid, which apart from some cosmetics, was what I needed.

Any help appreciated.

GavinR



More information about the R-help mailing list