当scales =“ free”和space =“ free”时,更改构面的绘制范围

时间:2018-09-07 23:02:53

标签: r ggplot2

我编写了以下代码,以使用构面创建实质上是断开的x轴。与ggplot 2.2.1版和R版本3.4.3配合使用时效果很好。当我升级到ggplot版本3.0.0,R版本3.5.1时,第二个构面的绘制范围使它和其标签不可读。有什么方法可以指定绘图范围,以便查看数据吗?刻面宽度应至少不等于刻面标签宽度吗?这是错误吗?

library(ggplot2)

dd <- data.frame(hours = c(.1, .3, 1, 1.5, 6, 8, 24), 
                 Estimate = c(0.35, -3.6, -2.5, 0.7, -4, -6, -4.4), 
                 low = c(-4.3, -8.2, -7.2, -4.2, -8.6, -10.1, -9),
                 high = c(5.7, 1.0, 2.2, 5.6, 0.6, -.77, 0.17),
                 Day = c(rep("Day 1", 6), "Day 2" ))

makeplot <- function(x){
ggplot(data=x,
       aes(x=hours, y=Estimate,group=1))+ 
  facet_grid(~Day,scales="free",space="free") +
  geom_point(size=3) + 
  geom_line(size=.9) + 
  geom_segment(aes(x=hours, xend=hours,y=low,yend=high),size=1) +
  ylab(label=expression(paste("Change in y \n a versus b"))) +
  xlab(label="Hours elapsed") +
  geom_hline(yintercept=0, color="grey") +
  ggtitle(paste0("Effect of x on y")) +
  scale_x_continuous(breaks=seq(0:24)) +
  theme_bw(30) + 
  theme(legend.key.size=unit(.5, "inches"),
        line=element_line(size=2),
        panel.border=element_rect(size=2),
        panel.grid=element_line(size=1),
        axis.title.x=element_text(vjust=0),
        axis.title.y=element_text(hjust=0,margin = margin(l = 0)),
        legend.title=element_text(vjust=0),
        legend.text.align=0,
        plot.margin = unit(c(1,1,1,2), "cm"))
}

makeplot(dd)
ggplot版本2.2.1,R版本3.4.3: enter image description here

ggplot版本3.0.0,R版本3.5.1: enter image description here

1 个答案:

答案 0 :(得分:1)

我实际上无法使用此代码在另一台机器上重现3.4.3中正确间隔的图,但是Z.lin的解决方案有效。轴断裂也需要指定

... + scale_x_continuous(breaks=1:24,expand = c(0, 0.5))