Home > Back-end >  How to prevent RMarkdown from cutting off my Python graphs when using the R-reticulate package?
How to prevent RMarkdown from cutting off my Python graphs when using the R-reticulate package?

Time:08-16

I have some simple plots in an Rmarkdown file plotted with matplotlib in a python chunk using the R-Reticulate package. But for some reason, the graphs always get squished no matter how I specify the figsize in python. It seems as if it is a problem with RMarkdown because I have plotted the same graphs in a .py file and they come out fine. Does anyone know how to prevent this resizing from RMarkdown?

Here is the code:

```{python, message=FALSE, results='hide', fig.keep='all'}
fig = plt.figure(figsize=(10,8))
plt.xlabel('Log Dispersion (km/s)', fontsize='x-large', fontweight='bold')
plt.ylabel(r'Log Black Hole Mass ($M_\odot$)', fontsize='x-large', fontweight='bold')
plt.scatter(data.SIG, data.MBH, label='data')
plt.show()
```

Here is the output in RMarkdown:

enter image description here

As you can see, it gets cutoff. Meanwhile, this same code in a .py file is totally fine. I have tried changing the figure size in fig = plt.figure(figsize=(10,8)) and it does absolutely nothing.

CodePudding user response:

I'm still not able to duplicate the issue you're having. The following is a chunk that will add Resize Sensor to the page.

```{r spicy, engine="js", include=FALSE, results="asis"}

scrp = ["https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/1.2.3/ElementQueries.min.js",
        "https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/1.2.3/ResizeSensor.js"];

setTimeout(function(){ // this function adds the URLs to the HTML <head>
  for(i=0; i < scrp.length; i  ) {
    script = document.createElement('script');
    script.src = scrp[i];
    script.type = "text/javascript";
    document.head.appendChild(script);
  }
  ElementQueries.listen(); // just listen!!
}, 200); //wait a sec!

```

Since this is a notebook, you may want to add echo=F to the chunk options.

If this doesn't work, look at any other global settings you've set.

  • For example, do you have any configurations established in your YAML?
  • Or is it just who, when, and output?
  • Did you set default figure sizes?
  • Are some plots okay and others not? If so, what differs?
  • Do you have columns or rows specified?
  • Do you have styles specified?

Another thing that's worth mentioning—base R plots and ggplot render as images, while graphs from packages like plotly or highchart render as HTML. Matplotlib renders as an image.

  • Related