Graphing matplotlib with Python code in a R Markdown document

前端 未结 4 1349
半阙折子戏
半阙折子戏 2021-01-11 09:14

Is it possible to use Python matplotlib code to draw graph in RStudio?

e.g. below Python matplotlib code:

import numpy as np
import matplotlib.pyplot         


        
4条回答
  •  -上瘾入骨i
    2021-01-11 09:43

    I have been working with reticulate and R Markdown and you should specify your virtual environment. For example my R Markdown starts as follows:

    {r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE, warning = FALSE, cache.lazy = FALSE)
    library(reticulate)
    
    use_condaenv('pytorch') ## yes, you can run pytorch and tensor flow too
    

    Then you can work in either language. So, for plotting with matplotlib, I have found that you need the PyQt5 module to make it all run smoothly. The following makes a nice plot inside R Markdown - it's a separate chunk.

    {python plot}
    import PyQt5
    import numpy as np
    import pandas as pd
    import os
    
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import figure
    
    data = pd.read_csv('Subscriptions.csv',index_col='Date', parse_dates=True)
    
    # make the nice plot
    # set the figure size
    fig = plt.figure(figsize = (15,10))
    
    # the series
    ax1 = fig.add_subplot(211)
    ax1.plot(data.index.values, data.Opens, color = 'green', label = 'Opens')
    
    # plot the legend for the first plot
    ax1.legend(loc = 'upper right', fontsize = 14)
    
    plt.ylabel('Opens', fontsize=16)
    
    # Hide the top x axis
    ax1.axes.get_xaxis().set_visible(False)
    
    #######  NOW PLOT THE OTHER SERIES ON A SINGLE PLOT
    
    # plot 212 is the MI series
    
    # plot series
    ax2 = fig.add_subplot(212)
    ax2.plot(data.index.values, data.Joiners, color = 'orange', label = 'Joiners')
    
    # plot the legend for the second plot
    ax2.legend(loc = 'upper right', fontsize = 14)
    
    # set the fontsize for the bottom plot
    plt.ylabel('Joiners', fontsize=16)
    
    plt.tight_layout()
    plt.show()
    

    You get the following from this:

提交回复
热议问题