Although I use a horizontal barplot as an example here, that itself is not the issue. The general issue is how to deal with the white space that is created around ggplots in rmarkdown after using
+coord_fixed(ratio=...)
To reduce the space used by barplots, especially with few factor, I prefer horizontal barplots, where I use coord_fixed(ratio=...) to have a sensible ratio between width and length of the bars.
The plot itself looks the way I want to (see first example below), but it has a lot of white space around it, which I tried to remove by using fig.height = ... in the knitr-header. As the next example shows, this didn't turn out well.
library(ggplot2)
library(ggstance)
library(dplyr)
X <- data.frame(X = sample(c("A", "B"), 30, replace = TRUE))
X <- X %>% group_by(X) %>% summarise(n = n())
ggplot(X, aes(y = X, x = n))+
geom_barh(stat = "identity")+
coord_fixed(ratio = 1)+
ggtitle("blub")
Using this inside rmarkdown where I used x = 3 ; x = 1 ; x=0.5:
```{r,fig.height = x}
# see code above
```
This results in:
fig.height=3
fig.height=1
fig.height=0.5
What I hoped it would do:
- Crop the white margins
- while keeping the plot (plot + (axis)titles) area itself constant
The latter clearly doesn't happen as the plot area gets narrower and the titles are moved to the inside of the plot.
I don't know if the solution is to be found inside ggplot or inside knitr. On top of that, an ideal solution should be easily automated for use inside a loop (adapt the solution to changing number of factors).