R Markdown: How can I make RStudio display Python plots inline instead of in new window?

前端 未结 1 764
南旧
南旧 2020-12-05 15:19

So, I\'ve been using R Markdown extensively lastly, and I\'m pretty satisfied with what it can do.

However, I\'m having a problem with python plots. I have a chunk o

1条回答
  •  [愿得一人]
    2020-12-05 15:32

    To expand on my earlier comment, I will elaborate with a complete answer. When using matplotlib, the plots are rendered using Qt, which is why you are getting popup windows.

    If we use fig.savefig instead of pyplot.show and then pyplot.close we can avoid the popup windows. Here is a minimal example:

    ---
    output: html_document
    ---
    
    ## Python *pyplot*
    
    ```{python pyplot, echo=FALSE}
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)
    
    fig, ax = plt.subplots()
    ax.plot(t, s)
    
    ax.set(xlabel='time (s)', ylabel='voltage (mV)',
           title='About as simple as it gets, folks')
    ax.grid()
    
    fig.savefig("pyplot.png")
    plt.close(fig)
    ```
    
    ```{r, echo=FALSE}
    knitr::include_graphics("pyplot.png")
    ```
    

    Which produces the following without any process interruption:

    Source: matplotlib.org

    N.B. According the the release notes for RStudio v1.2.679-1 Preview, this version will show matplotlib plots emitted by Python chunks.

    Update

    Using the latest preview release mentioned above, updating the chunk to use pyplot.show will now display inline as desired.

    ```{python pyplot, echo=FALSE}
    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)
    
    fig, ax = plt.subplots()
    ax.plot(t, s)
    
    ax.set(xlabel='time (s)', ylabel='voltage (mV)',
           title='About as simple as it gets, folks')
    ax.grid()
    
    plt.show()
    ```
    

    For Anaconda users

    If you use Anaconda as your python distribution, you may experience a problem where Qt is not found from RStudio due to problem with missing path/environment variable.

    The error will appear similar to:

    This application failed to start because it could not find or load the Qt platform plugin "windows" in "", Reinstalling the application may fix this problem.

    A quick fix is to add the following to a python chunk to setup an environment variable.

    import os
    os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = '/path/to/Anaconda3/Library/plugins/platforms'
    

    Replacing /path/to with the relevant location to your Anaconda distribution.

    0 讨论(0)
提交回复
热议问题