4

I'm trying to show a wordcloud2 wordcloud, but it only works in an html-knitted Rmd file. This works:

---
title: "Untitled"
output: html_document
---

```{r wordcloud}
library(wordcloud2)
wordcloud2(demoFreq)
```

But this does not:

---
title: "Untitled"
output: pdf_document
---

```{r wordcloud}
library(wordcloud2)
wordcloud2(demoFreq)
```

It will knit with always_allow_html: yes in the YAML, but the wordcloud doesn't show up:

---
title: "Untitled"
output: pdf_document
always_allow_html: yes
---

```{r wordcloud}
library(wordcloud2)
wordcloud2(demoFreq)
```

I'm thinking maybe to save the figure as an image, then load it in the .Rmd, but that seems clumsy. Better ideas?

wordsforthewise
  • 13,746
  • 5
  • 87
  • 117

1 Answers1

8

One way to do it, as I said, is to save as an image and load it in .Rmd. Not too bad actually:

---
title: "Untitled"
output: pdf_document
---

```{r wordcloud}
library(wordcloud2)
library(webshot)
library(htmlwidgets)
my_graph <- wordcloud2(demoFreq, size = 1.5)
saveWidget(my_graph, "tmp.html", selfcontained = F)
webshot("tmp.html", "wc1.png", delay = 5, vwidth = 2000, vheight = 2000)
```
![wordcloud](wc1.png)

The delay argument needs to be big enough to let the html fully render; if you watch a wordcloud2 generate, it takes a few seconds. 5 seconds seems enough for this, but you may have to increase it for bigger/more complex wordclouds, or if your computer is slow.

wordsforthewise
  • 13,746
  • 5
  • 87
  • 117
  • Also described here: https://github.com/Lchiffon/wordcloud2/issues/8#issuecomment-255638090 and this post: https://stackoverflow.com/a/51760065/4549682 – wordsforthewise Apr 17 '19 at 00:21
  • Do you get the same image when viewed in R, once stored as html file and then when stored as .PNG? For me every of these images is slightly different (color and position), even after using shuffle =False in wordcloud2. – Sapiens Jul 26 '21 at 16:46
  • Not sure, it's been a long time since I've run this. I'll take your word for it. There must be another random seed to set somewhere. Maybe try setting the global random seed. – wordsforthewise Jul 28 '21 at 02:19