0
  1. I want my program to display map created with matplotlib that uses .csv file and display that map alongside with JSON data. Map alone actually works, but I want it to open on next page with JSON data. Now I can only go to next page that contains JSON data after I close the map window which opens on home page. On next page I get "Failed to load resource: the server responded with a status of 404 (Not Found)" from DevTools.
  2. And other problem is after a while it doesn't even open,I get "main thread is not in main loop" error. Closing terminal and putting again virtual env and python manage.py runserver works but then it happens again. And if you leave JSON alone, it works perfectly so I guess map is the problem.

This is the main page. So you gotta click X on map window then it proceed to next page

This is the next page, you can even go back and forth when map is minimalized

from django.shortcuts import render
import json
import urllib
import matplotlib
import matplotlib.pyplot as plt

from mpl_toolkits.basemap import Basemap
import numpy as np
import pandas as pd

def Last1Hour(request):
    # this is for reading and displaying JSON data
    urlData = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson'
    webURL = urllib.request.urlopen(urlData)  
    data = webURL.read()

    if request.method == 'GET':
        json_data = json.loads(data)
        earthquakes_data = [] 
        for earthquake in json_data['features']:            
            place = earthquake['properties']['place']       
            magnitude = earthquake['properties']['mag']
            longitude = format(earthquake['geometry']['coordinates'][0], '.3f') 
            latitude = format(earthquake['geometry']['coordinates'][1], '.3f') 
            earthquakes_data.append({'place': place,'magnitude': magnitude,
                                    'longitude': longitude,  'latitude': latitude})

    # Here is code for making map
    m = Basemap(projection='merc', llcrnrlat=-80, urcrnrlat=80,
                    llcrnrlon=-180, urcrnrlon=180, resolution='c')
    m.drawcoastlines()
    m.drawcountries()
    path = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.csv"  # this is the .csv file
    data1 = pd.read_csv(path)             # reading the data set 
    lon = []                            # extracting information from data set
    for i in data1['longitude']:
        lon.append(i)
    lat = []
    for i in data1['latitude']:
        lat.append(i)
    x, y = m(lon, lat)                   #converting longitude ,laitude  to x ,y
    sizes = data1['mag'].values ** 2     # different size of plot point
    x = np.array(x, dtype=float)
    y = np.array(y, dtype=float)
    sizes = np.array(sizes, dtype=float)
    m.scatter(x, y, marker='o', c=data1['mag'], s=sizes, label=data1['mag'])     #plotting the data
    plt.savefig(r'C:\Users\piotr\EarthQuake\static\map7d.png')     # saving the data in static file
    plt.show()
    return render(request, 'Last1Hour.html', {'json_data': earthquakes_data}, )  

Here is my .html code

{% load static %}
<h1>Last 1h Earthquakes Data</h1>
<table>

  <body>
   
    <img src="{% static 'map.png' %}" alt="Map">
    
    <th>Place</th>
    <th>Magnitude</th>
    <th>Longitude</th>
    <th>Latitude</th>

  </tr>
  {% for earthquake in json_data %}
  <tr>
    <td>{{ earthquake.place }}</td>
    <td>{{ earthquake.magnitude }}</td>
    <td>{{ earthquake.longitude }}</td>
    <td>{{ earthquake.latitude }}</td>
   
  </tr>
  {% endfor %}
</table>
</body>

In setting.py I included

import os
...
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

In urls.py I added

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('EarthQuakeApp.urls'))
]+ (settings.STATIC_URL, document_root=settings.STATIC_ROOT)

I have tried changing in .html file , problem was the same. Tried to put outside the for loop, didn't help, changed nothing to be real.

Piotr
  • 1
  • 2
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Feb 10 '23 at 13:44

1 Answers1

0

Plt.show() is a blocking function. This question provides a solid overview of how to display plots in a non-blocking manner.

What is currently happening in your code is that execution is blocked until you close the window. Following this, the line:

return render(request, 'Last1Hour.html', {'json_data': earthquakes_data}, )  

is called and your view is generated. This is why you cannot see the JSON data.

As an aside, I'm not positive what you're aiming for with your code here, but if you're trying to display plots on your webpage, this is a pretty unusual way to do it. Whilst I'm sure you could pass an image of your plot to the view, I think you would be better off passing your data to the frontend and then generating a plot through javascript.

user1814893
  • 301
  • 2
  • 6
  • Thank you, I will dive into this thread, looks like it has some answers Yes, now I see there are better ways to do that. I just went the hard way, i'm just starting as u can see prolly :) – Piotr Feb 11 '23 at 16:52