ggplot2 scale_x_continuous limits or absolute

蹲街弑〆低调 提交于 2019-12-12 11:08:41

问题


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()

回答1:


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:



来源:https://stackoverflow.com/questions/9776927/ggplot2-scale-x-continuous-limits-or-absolute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!