【问题标题】:facet plots with different yaxis scales具有不同 y 轴刻度的小平面图
【发布时间】:2016-12-12 05:29:05
【问题描述】:

绘制具有不同比例的多个方面。简单例子:

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=,顶部刻面将变得无趣。有没有办法将这些信息显示为方面(而不是在单独的页面上),同时仍然传达尺度上的巨大差异。例如,我怎样才能将顶面的 ymax 设置为更大的数字?

【问题讨论】:

  • 我相信你可以通过gridExtra做到这一点。
  • scales = free 听起来像是合适的命令。如果您想控制特定面板的限制,您始终可以使用geom_blank() 添加一个虚拟层

标签: r ggplot2


【解决方案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)

【讨论】:

    猜你喜欢
    • 2012-04-24
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2021-11-07
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多