Search code examples
rggplot2scale

ggplot2 scale_x_continuous limits or absolute


I am using the following ggplot2 v0.9 scale_x_continious logic in a loop (by county name) in an attempt to plot each county's data on a seperate plot with identical x scales.

MaxDays=365*3;
p <- p + scale_x_continuous(limits=c(0,MaxDays))
p <- p + scale_x_continuous(breaks=seq(0,MaxDays,60))

The logic works great, if all counties have data >= MaxDate. However, if the number of days is less than the MaxDate the charts x scales are not uniform (i.e say 0 - 720 days)

How can set the scalse to be absolute instead of a limit?

Any assistance woudl be greatly appreciated

############################################
###  Sample Data Below
############################################

# County 1 data
Days=seq(1,30,1)
Qty=Days*10
County=rep("Washington",length(Days))
df1=data.frame(County, Qty, Days)

# County 2 data
Days=seq(1,15,1)
Qty=Days*20
County=rep("Jefferson",length(Days))
df2=data.frame(County, Qty, Days)

# County 1 and 2 data
df3=rbind(df1,df2)

# calculate ranges for x scales
yrng=range(df3$Qty)
xrng=range(df3$Days)

# Scatter Plots
fname=paste("C:/test",".pdf",sep="");
pdf(fname,10,8,onefile=TRUE,paper="a4r");

p <- ggplot()
cnty=unique(df3$County)
n=length(unique(df3$County))
for (i in 1:n){
  df4<-subset(df3, County==cnty[i])
  p <- ggplot(df4, aes(x=Days, y=Qty))
  p <- p + geom_point()
  p <- p + opts(title=cnty[i])
  p <- p + scale_x_continuous(limits=c(xrng[1],xrng[2])) 
  p <- p + scale_x_continuous(breaks=seq(xrng[1],xrng[2],1))
  p <- p + coord_cartesian(xlim=c(xrng[1],xrng[2]))
print(p);
}
dev.off()

Solution

  • p <- p + coord_cartesian(xlim=c(0, MaxDays))
    

    EDIT: based on comments.

    Your problem is that the second scale_x_continuous() is replacing, not augmenting, the first, so the limits are not kept.

    You can replace the lines

    p <- p + scale_x_continuous(limits=c(xrng[1],xrng[2])) 
    p <- p + scale_x_continuous(breaks=seq(xrng[1],xrng[2],1))
    

    with

    p <- p + scale_x_continuous(limits=c(xrng[1],xrng[2]), 
                                breaks=seq(xrng[1],xrng[2],1))
    

    which gives something like this:

    enter image description here