Lukas D. Sauer
Lukas D. Sauer

Reputation: 513

RMarkdown and ggplot: Axis labels cut off

In an RMarkdown PDF document, I am generating a heatmap with rather long tick labels. For some reason, this causes the y-axis label and the colour legend to be cut off. I already attempted several tricks in order to fix this, but so far to no avail. Here is my reprex:

---
title: "Test"
output: pdf_document
draft: true
  
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
    echo = FALSE, fig_crop=FALSE
)
```

```{r dependencies, include=FALSE}
library(tidyverse)
options(print_format="tex")
```

```{r, include=FALSE}
# Dummy data
set.seed(1234)
Count = rep((1:5), 8)
Gadget = rep(c("BANANA", "APPLE", "PEAR", "ORANGE", "ENCYCLOPEDIA", "XYLOPHONE", "TOMATO", "POTATO"), each=5)
GadgetScore = runif(40, 0, 100)
data = data.frame(Count, Gadget, GadgetScore)
```

```{r}
# Generate heatmap
maxi = max(data$GadgetScore, na.rm=TRUE)
mini = min(data$GadgetScore, na.rm=TRUE)
midi = mini+(maxi-mini)/2
ggplot(data, aes(Count, Gadget, fill=GadgetScore)) + geom_tile() +
  scale_fill_gradient2(name="Gadget score value", low="red", mid="yellow", high="green", midpoint=midi) +
  labs(x="Count", y="Gadgets")
```

Here is the output: Heatmap with cropped axis labels and color legend

As you can see, the y-axis label Gadgets on the left hand side, and the colour legend label Gadget score value on the right hand side are cropped. As I said, I already tried a couple of hints from StackOverflow, but so far, none of them worked.

Trick 1: Following this post, I tried adding

theme(axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank())

to the ggplot elements.

Trick 2: Following this post, I tried to adapt the width of the plot chunk with something like

fig.width = 5

Trick 3: Following this post, I tried adding

theme(plot.margin = margin(100, 100, 100, 100))

to the ggplot elements.

Trick 4: I tried adding the option crop = FALSE and fig_crop=FALSE to the setup chunk.

Unfortunately, none of these tricks worked. Any help will be much appreciated.

Upvotes: 3

Views: 5108

Answers (2)

Lukas D. Sauer
Lukas D. Sauer

Reputation: 513

In my case, the cropping error was related to a deprecated version of GhostScript. After updating GhostScript to the latest version (9.54.0), I can run the reprex without any image cropping issues.

Upvotes: 2

Isaac
Isaac

Reputation: 986

The code works perfectly for me. However, you can check the alignment of the image, maybe if you place it a bit more to the right you can see the label. For this try in the last chunk to add {r, fig.dim = c(5, 2.5), fig.align = 'right'}

Upvotes: 0

Related Questions