使用ggplot和facet_wrap将Y轴设置为0

Pat*_*bug 4 r ggplot2 facet-wrap

我正在使用以下代码:

x_breaks <- seq(as.Date("2010/1/1"), as.Date("2015/4/1"), "months")
x_labels <- as.character(x_breaks, format="%b%y")

thousand_formatter<-function(x){
  return(as.integer(x))
}

vLines <- data.frame('Date'=as.Date('2014/1/1'))
vLines <- rbind(vLines,vLines)
vLines$Date[1] <- as.Date('2013/3/4')
vLines$Date[2] <- as.Date('2014/6/2')

vLines$grp <- c('Complex Cases (except CD cases)','CD cases')

p <- ggplot(toPlot[1:261,], aes( Date, value)) + theme_bw() +ylab('Transactions') + xlab('') +
  scale_x_date(breaks=x_breaks, labels=x_labels)
p <- p + geom_line(aes(colour = variable, fill= variable),size=1.5) +
  theme(axis.text.y=element_text(hjust=0, angle=0), 
        axis.text.x = element_text(hjust=1, angle=45),
        panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.grid.major.x=element_line(color='grey90',linetype='dashed'),
        panel.grid.major.y=element_line(color='grey90',linetype='dashed'),
        plot.title=element_text(size=20),
        axis.text=element_text(size=10),
        legend.key=element_blank(),
        legend.title=element_blank()) +
  scale_y_continuous(label=thousand_formatter) +
  ggtitle('Some Title')+
  scale_fill_manual(values=c("#a6cee3","#1f78b4","#b2df8a","#33a02c","#fb9a99","#e31a1c","#fdbf6f","#ff7f00","#cab2d6")) +
  facet_wrap(~OrderType,nrow=3,scales="free") +
  geom_vline(data=vLines,aes(xintercept=as.numeric(Date),colour=grp,linetype=grp),size=1) 
#   scale_y_continuous(expand = c(0, 0))
p
ggsave('SomeTitle.png', scale=2)
Run Code Online (Sandbox Code Playgroud)

得到以下情节:

在此输入图像描述

输出dput(head(toPlot))是:

structure(list(Date = structure(c(15065, 15095, 15218, 15309, 
15371, 15400), class = "Date"), OrderType = structure(c(1L, 1L, 
1L, 1L, 1L, 1L), .Label = c("Delivery", "eFiling", "Filing", 
"ProcessServing", "Research"), class = "factor"), variable = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("Orders", "Revenue"), class = "factor"), 
    value = c(1, 1, 1, 2, 1, 3)), .Names = c("Date", "OrderType", 
"variable", "value"), row.names = c(NA, 6L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)

如果我们仔细注意,我们可以看到位置(2,1),(2,2)和(3,1)的图形不是从零开始.

我希望Y轴从零开始,任何指针都会非常感激.

这个问题可能有一个重复的强制原点从ggplot2(R)的0开始,但它的解决方案并没有解决我的问题.换句话说,我尝试使用,scale_y_continuous(expand = c(0, 0))但它没有解决我的问题.在任何时候我都不使用这两个scale_y_continuous()陈述,总是评论一个.

我的数据集可以在这里找到.

小智 6

您可以使用scale_y_continuous关键词limits:

scale_y_continuous(limits=c(0,max(toPlot$value)))
Run Code Online (Sandbox Code Playgroud)

  • 如果添加scale_y_continuous(limits = c(0,NA)),它会保持facet的最大值,但是将它们全部设置为零. (13认同)
  • 好吧,它没有解决方面的问题,不是吗?(至少我们在这里使用自由秤) (5认同)
  • @jenwen的upvote,解决了使用构面时的问题 (2认同)