[R] barplot with more than 1 variable

Jim Lemon jim at bitwrit.com.au
Mon Feb 20 08:26:09 CET 2012


On 02/19/2012 11:31 PM, Francesco Sarracino wrote:
> Dear R listers,
> I am trying to produce a simple (for a stata user) barplot with 4
> countries on the x axis, each country observed in 2 subsequent years
> and 3 variables.
> Basically, I should have three bars for each year for each country. I
> am attaching the chart I made in Stata, but I am not sure you'll
> manage to see it!
>
> I did the following:
> #here I create the data-set TUSE2. The vectors mw, st and all are the
> three variables I'd like to plot in each of the two years of the
> variable year3 for each country.
>
> country<- c("United States","United
> States","Italy","Italy","Germany","Germany","Netherlands","Netherlands")
> year3<- c(1, 2, 1, 2, 1, 2,1 , 2)
> mw<- c( 245.8, 255.9,  248.5, 207.4,263.9, 197.7, 174.2, 189.5)
> st<- c( 200.5, 218.0,  236.1, 237.3, 220.5, 242.7, 221.0, 206.0)
> all<- c( 446.3, 473.9,  484.6, 444.7,484.5, 440.4, 395.2, 395.5)
> TUSE2<- data.frame(country, year3, mw, st, all)
> attach(TUSE2)
>
> #I load the library ggplot (But if you know of alternative techniques,
> I'll be happy to try them out)
>
Hi Francesco,
You can try this to get something like your example. change the "mar" 
argument to leave space for a legend and use par(xpd=TRUE) to put it 
outside the plot if you want a legend.

# first stretch the data out to long form
library(prettyR)
TUSE3<-rep_n_stack(TUSE2,to.stack=c("mw","st","all"),
  stack.names=c("work_type","output"))
# start a wide graphics device
x11(width=10)
library(plotrix)
# get the order of levels in work_type right
TUSE3$work_type<-factor(TUSE3$work_type,levels=c("mw","st","all"))
# display it as a nested bar plot
barNest(output~country+year3+work_type,TUSE3,showall=FALSE,
  FUN="mean",main="Type of work in 4 countries in two intervals",
  ylab="Value of work",
  barlabels=list("",c("Germany","Italy","Netherlands","United States"),
  c("1985-91","2000-03"),levels(TUSE3$work_type)),
  col=list("white","white","white",c("gray80","gray50","gray20")))

Jim



More information about the R-help mailing list