How to keep R code and figure on the same page in

2019-04-08 04:55发布

问题:

Is there a way in RMarkdown to force R code and the figure that it produces to appear on the same page please? I am using Knit pdf. For example,

```{r}
ggplot(df, aes(x = x, y = y, col = sex_f)) + geom_point() +
  ggtitle("Data from Children") +
  labs(x = "Age (months)", y = "Height (cms)", col = "Child Gender") +
  geom_smooth(method = "lm", se = FALSE) + 
  facet_grid(sex_f ~ town_f)
```

(which is not reproducible) produces code on one page and a plot on the next page. I have tried setting the figure width and height globally, for example

```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.width = 4, fig.height = 3, 
                       fig.path = 'Intro_Figs/',
                       fig.show = 'asis',
                       fig.align = 'center',
                       warning = FALSE, message = FALSE)
```

with very small values, but this does not prevent all bad page breaks. Thank you.