2016-08-05 73 views
1

绘制具有不同刻度的多个刻面。简单的例子:具有不同yaxis刻度的刻面图

require(data.table) 
require(ggplot2) 

nr <- 10000 
inp.dt <- rbind(
    data.table(type="A", month=sample(seq(as.Date("2011/1/1"), as.Date("2012/1/1"), by="month"), nr, replace=T)), 
    data.table(type="B", month=sample(seq(as.Date("2011/1/1"), as.Date("2012/1/1"), by="month"), 100*nr, replace=T)) 
) 
plot.dt <- inp.dt[, .(count=.N), .(type,month)] 

mnth <- sort(unique(plot.dt[["month"]])) 
plot.dt[, ":="(type=factor(type), month=factor(month, label=format(mnth, format="%Y-%b"), ordered=TRUE))] 

g <- ggplot(plot.dt, aes(x=month, y=count)) + 
    geom_bar(stat="identity") + expand_limits(y=0) + facet_grid(type~., scales="free_y") 
print(g) 

如果我删除scales=顶端方面变得无趣。是否有方法将这些信息显示为方面(不在单独的页面上),同时仍然表达了广度差异。例如,我怎样才能将top facet的ymax设置为更高的数字?

+1

我相信你可以用'gridExtra'来做到这一点。 –

+1

'scales = free'听起来像是合适的命令。如果你想控制特定面板的限制,你总是可以用'geom_blank()'添加一个虚拟层 – baptiste

回答

1

我不确定你想要的尺度设置为什么,所以我只是随便挑选了一些数字。

require(data.table) 
require(ggplot2) 

nr <- 10000 
inp.dt <- rbind(
    data.table(type="A", month=sample(seq(as.Date("2011/1/1"), as.Date("2012/1/1"), by="month"), nr, replace=T)), 
    data.table(type="B", month=sample(seq(as.Date("2011/1/1"), as.Date("2012/1/1"), by="month"), 100*nr, replace=T)) 
) 
plot.dt <- inp.dt[, .(count=.N), .(type,month)] 

mnth <- sort(unique(plot.dt[["month"]])) 
plot.dt[, ":="(type=factor(type), month=factor(month, label=format(mnth, format="%Y-%b"), ordered=TRUE))] 

# g <- ggplot(plot.dt, aes(x=month, y=count)) + 
# geom_bar(stat="identity") + expand_limits(y=0) + facet_grid(type~., scales="free_y") 
# print(g) 

g1 <- ggplot(plot.dt[plot.dt$type=="A",], aes(x=month, y=count)) + scale_y_continuous(limits=c(0,1500))+ 
    geom_bar(stat="identity") + expand_limits(y=0) #+ facet_grid(type~., scales="free_y") 
print(g1) 

g2 <- ggplot(plot.dt[plot.dt$type=="B",], aes(x=month, y=count)) + scale_y_continuous(limits=c(0,800000))+ 
    geom_bar(stat="identity") + expand_limits(y=0) #+ facet_grid(type~., scales="free_y") 
print(g2) 


install.packages("gridExtra") 
library(gridExtra) 
gA <- ggplotGrob(g1) 
gB <- ggplotGrob(g2) 


p <- arrangeGrob(
    gA, gB, nrow = 2, heights = c(0.80, 0.80)) 

plot(p)