Lyndon Walker
Lyndon Walker

Reputation: 105

Reducing panel height/width in a ggplot & cropping the white space in R Markdown

Please don't close this and tell me the answer is on Remove space between plotted data and the axes because that is not the same plot and does not work here. Using expand makes the bar large.

My original issue was too much panel which is detailed below and I solved using

library(patchwork)
plot11f + plot_layout(ncol = 1,nrow =5)

I was able to get the nice skinny plot with less grey, but when in my markdown document it has a big white space under it. Using plot.margins doesn't help, it chops off my axis labels and still gives the big white space.

enter image description here

--- Original question --- I have produced the following ggplot (code and dummy data below) but I want to reduce the height of the grey panel bits (where I have scribbled in red) to make the graph shorter (I might even shrink the width of the bar further but need to know how to reduce the grey background panel first).

tableq11f<-data.frame(Q11f<-c("A","B","C","D","E"), percent<-c(0.03,0.07,0.22,0.46,0.22))
plot11f<-ggplot(data=tableq11, aes(x=percent, y="Q11", fill=Q11f))+
  geom_col(position = "fill", show.legend = FALSE, width=0.5)+ 
  scale_fill_brewer(palette="Blues")+theme(axis.title.x=element_blank(),
  axis.title.y=element_blank(),axis.text.y=element_blank(),axis.ticks.y=element_blank())+ 
  scale_x_continuous(labels = scales::percent)

ggplot to alter

More like this

better image

Upvotes: 0

Views: 1443

Answers (1)

Iroha
Iroha

Reputation: 34741

The empty space is there because you used patchwork to create a grid of your plot and four empty rows which isn't a suitable way to achieve your goal. Instead, reduce the space between the bar and plot margins using scale_y_discrete(expand = expansion(mult = .075)) and decrease the width of the bar in geom_col(), and finally as mentioned in the comments, set an appropriate figure size for the plot in the markdown chunk options.

---
title: "Untitled"
output: word_document
---

```{r, echo=FALSE, fig.width=5, fig.asp = .15}

library(ggplot2)

tableq11f<-data.frame(Q11f=c("A","B","C","D","E"), percent=c(0.03,0.07,0.22,0.46,0.22))

ggplot(data = tableq11f, aes(x = percent, y = "Q11", fill = Q11f)) +
  geom_col(position = "fill",
           show.legend = FALSE,
           width = 0.1) +
  scale_fill_brewer(palette = "Blues") +
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank()
  ) +
  scale_x_continuous(labels = scales::percent) +
  scale_y_discrete(expand = expansion(mult = .075))
    
```

Which gives:

enter image description here

Upvotes: 2

Related Questions