2016-08-05 22 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)