ggplot2 scale_x_continuous极限或绝对 [英] ggplot2 scale_x_continuous limits or absolute

查看:500
本文介绍了ggplot2 scale_x_continuous极限或绝对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在循环使用以下ggplot2 v0.9 scale_x_continious逻辑(按县名),以尝试在每个具有相同x比例的图上绘制每个县的数据.

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

如果所有县的数据均大于等于MaxDate,则逻辑工作原理很好.但是,如果天数少于MaxDate,则图表x的比例尺会不一致(例如0-720天)

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?

任何帮助将不胜感激

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

推荐答案

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

基于评论.

您的问题是第二个scale_x_continuous()将替换第一个scale_x_continuous(),而不是增加第一个scale_x_continuous(),因此不会保留限制.

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

您可以替换行

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 + scale_x_continuous(limits=c(xrng[1],xrng[2]), 
                            breaks=seq(xrng[1],xrng[2],1))

它给出了这样的内容:

这篇关于ggplot2 scale_x_continuous极限或绝对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆