RuntimeError: main thread is not in main loop using Matplotlib with Django
Asked Answered
O

2

5

I am creating a Matplotlib figure to display in a HTML template in my Django application. I send this figure to the HTML by saving it under my static files, and then loading an img tag with the saved .png. I do this in my views.py after getting a reference to the figure.

        # Get analysis visualization chart
        figure = analyser.visualize_tweets(emotions)

        # Save figure in static folder as png
        figure.savefig('static/analysis_figures/figure.png')

        # Inject html with figure path
        response['analysis_figure_path'] = 'analysis_figures/figure.png'

return render(request, 'landing_page/index.html', response)

My HTML is something like this:

<img src={% static analysis_figure %} alt="">

However, this caused the RuntimeError: main thread is not in main loop to happen when the function in my views.py is called a second time (if it's called once everything works properly). To prevent this error, I moved saving the Matplotlib figure to main() as to run in the main thread and then call it in my original function. This fixed the error, but prevents my HTML from reloading so every time the user submits a query the new figure is displayed over the previous one without the previous one being removed. Any ideas on any of the problems ?

Oleum answered 3/5, 2018 at 14:40 Comment(0)
C
11

I think this post explains what to do: How to clean images in Python / Django?

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

As explained here: https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server

To prevent that the new figure is displayed over the previous one use: plt.close() / figure.close()

Carbone answered 22/11, 2018 at 15:54 Comment(1)
Second link does not work, here is an updated link.Orourke
C
-1

I am using Matplotlib package, it is generating a graph in runtime that i changing from Matplotlib image object into normal PNG Image, then i inserted in my django web Application. Here, Every time the Graph Image changing frequently as my website so i converted into binary image object and runtime locally stored as image ! then i getting location address from URI.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt


plt.bar(x, y, tick_label = tick_label, 
width = 0.8, color = ['red','yellow', 'green']) 
    

plt.xlabel('x - axis') 

plt.ylabel('y - axis') 

plt.title('My bar chart!') 

plt.style.use('fivethirtyeight')
    
fig=plt.gcf()
plt.close()

`enter code here`# convert graph
buf=io.BytesIO()
fig.savefig(buf,format='png')        
buf.seek(0)
string =base64.b64encode(buf.read())

uri=urllib.parse.quote(string)

context={'imgdata':uri}
Calefacient answered 3/11, 2020 at 6:25 Comment(3)
Hi Ammy, thank you for your answer. Could you maybe add some comments on what your code does?Spontaneous
Yes, I am using Matplotlib package, it is generating a graph in runtime that i changing from Matplotlib image object into normal PNG Image, then i inserted in my django web Application. Here, Every time the Graph Image changing frequently as my website so i converted into binary image object and runtime locally stored as image ! then i getting location address from URI. These is I done because graph result is changing we have to update that's why !!Calefacient
Thank you, that makes sense, I just asked, because I was reviewing your answer and I thought an explanation might be usefull. Btw. I didn't downvote your answer.Spontaneous

© 2022 - 2024 — McMap. All rights reserved.