Is it possible to plot matplotlib in R Shiny using reticulate?

I'm trying to plot a chart in R shiny using python matplotlib, but I couldn't find a way to do this. I created a function in python and I call from R.

Here is my function .py

import matplotlib.pyplot as plt
import numpy as np 
import pandas as pd
def map_harvest(df): 
  df = pd.DataFrame.from_dict(df)
  treats = list(set(df['yldPlt']))
  treats.sort(key=lambda a: (float(a[1:-1].split(',')[0]), float(a[1:-1].split(',')[1])))
  color = ['red','orange','yellow', '#00cc00', 'lightgreen','blue']
  fig, ax= plt.subplots()
  ax.set_aspect('equal')
  data = list()
  for idx, t in enumerate(treats):
    data=np.array(list([g[1],g[2]] for g in zip(df['yldPlt'],df['x'], df['y']) if g[0] == t))
    plt.scatter(data[:,0],data[:,1], c = color[idx], s = 0.5, label = treats[idx])
  legend = plt.legend(title = "t/ha")
  for i in range (len(treats)):
    legend.legendHandles[i]._sizes = [30]

  ax.set_xticks([])
  ax.set_yticks([])
  plt.title('Mapa de Produtividade')
  fig.tight_layout()
  plt.show()

and here is my shiny code:

server <- function(input, output) {

  lm_map_prod_filter <- reactive({
    lm_map_prod_corn[lm_map_prod_corn$farmer == input$farmer,]
  })

   output$mapprodPlot <- renderPlot({
     map_harvest(lm_map_prod_filter())
   })

but what I'm getting is this:

the plot is off-page, I want the plot like the another plot, like an image without save the plot as image. Anyone know how do I do this?

Hi @lariteixeira, my hunch is that you'll want to use renderImage()/imageOutput() instead of renderPlot()/plotOutput(). The former is capable of rendering any image that resides on disk (or as a base64 encoded string) whereas the latter is designed specifically for the R graphics device.

To do that, you'll want to change plt.show() to plt.savefig() to save the matplotlib image to a file

plt.savefig('myplot.png')

Then have the renderImage() expression return a list that references that filename.

output$mapprodPlot <- renderImage({
     map_harvest(lm_map_prod_filter())
     list(src = 'myplot.png')
   })
5 Likes

oh, it works! But list(src = 'myplot.png') didn't work, so I changed to img(src = 'myplot.png'). Thanks so much.

If your question's been answered (even if by you), would you mind choosing a solution? (See FAQ below for how).

Having questions checked as resolved makes it a bit easier to navigate the site visually and see which threads still need help.

Thanks

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.