Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render Python plots in RMarkdown?

For the life of me, I can't get to render plots in RMarkdown using Python. The plots display in my Python Editor, but not when I switch to RStudio trying to build a PDF/HTML report. I've been all over the internet, everyone has an answer, but none has the solution to my issue. Here's the error message I get the attached error below:

enter image description here

Below I made up some data to show what I'm trying to achieve. Once the application hits the seaborn line it produces the attached error message in RStudio

knitr::opts_chunk$set(echo = TRUE)
library(reticulate)

Importing Required Packages

import pandas as pd
import numpy as np
from scipy.stats import uniform  # for training-and-test split
import statsmodels.api as sm  # statistical models (including regression)
import statsmodels.formula.api as smf  # R-like model specification
import matplotlib.pyplot as plt  # 2D plotting
import seaborn as sns
x = np.random.normal(0, 1, 20)
y = np.random.normal(0, 2, 20)
sns.scatterplot(x, y)
like image 377
user3813620 Avatar asked Sep 30 '26 04:09

user3813620


1 Answers

I found the answer here

All I needed was to add these two lines in the R setup chunk below the library(reticulate) call

matplotlib <- import("matplotlib")
matplotlib$use("Agg", force = TRUE)
like image 118
user3813620 Avatar answered Oct 01 '26 17:10

user3813620