Matplotlib always opens a Window for every plot instead of just writing it to a file

Viewed 151

I try to plot weather radar data to an image and show it using PyQt5. However, everything works fine - but the plots of matplotlib create problems.

When I start the program, it generates 2 empty plot windows and shows them. If I remove the two pl.close() statements, there would be another 2 plot windows (but these 2 with the plot images).

Can you help, why it always opens the plots?

I just want matplotlib to save the plots to a file, to open it later with PyQt. The plots are saved but the the appearing windows are irritating.

When I don't instantiate a PyQt Window, the plot windows appear for a few millisecs and then closes.

I am very new to PyQt and Matplotlib, and I know, the code is not very efficient and beautiful. But I try to build a mockup to learn, how that stuff works. This is my code:

import numpy as np
import matplotlib.pyplot as pl
import wradlib
import warnings
warnings.filterwarnings('ignore')
import requests
import os
import sys

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

# Setting environment Variable
os.environ["WRADLIB_DATA"] = "/home/luke/stationradar_viewer"

def load_radar_data():
    try:
        get_ipython().magic("matplotlib inline")
    except:
        pl.ion()


    RADAR_URL = 'https://opendata.dwd.de/weather/radar/sites/dx/tur/raa00-dx_10832-latest-tur---bin'
    r = requests.get(RADAR_URL)

    with open('/home/luke/stationradar_viewer/raa00-dx_10832-latest-tur---bin', 'wb') as f:
        f.write(r.content)
    
    filename = wradlib.util.get_wradlib_data_file('raa00-dx_10832-latest-tur---bin')

    one_scan, attributes = wradlib.io.read_dx(filename)

    pl.figure(figsize=(10, 8))
    ax, pm = wradlib.vis.plot_ppi(one_scan)
    ax = wradlib.vis.plot_ppi_crosshair((0,0,0), ranges=[40, 80, 128])

    cbar = pl.colorbar(pm, shrink=0.9)
    cbar.set_label("Reflectivity (dBZ)")

    pl.title('Reflectivity at {0}\nDWD radar Türkheim'.format(attributes['datetime']))
    pl.xlim((-128, 128))
    pl.ylim((-128, 128))

    pl.savefig('/home/luke/stationradar_viewer/tur_latest.png', dpi=(300), bbox_inches='tight')
    pl.close(None)

    ########

    RADAR_URL = 'https://opendata.dwd.de/weather/radar/sites/dx/fbg/raa00-dx_10908-latest-fbg---bin'
    r = requests.get(RADAR_URL)

    with open('/home/luke/stationradar_viewer/raa00-dx_10908-latest-fbg---bin', 'wb') as f:
        f.write(r.content)
    
    filename = wradlib.util.get_wradlib_data_file('raa00-dx_10908-latest-fbg---bin')

    one_scan, attributes = wradlib.io.read_dx(filename)

    pl.figure(figsize=(10, 8))
    ax, pm = wradlib.vis.plot_ppi(one_scan)
    ax = wradlib.vis.plot_ppi_crosshair((0,0,0), ranges=[40, 80, 128])

    cbar = pl.colorbar(pm, shrink=0.9)
    cbar.set_label("Reflectivity (dBZ)")

    pl.title('Reflectivity at {0}\nDWD radar Feldberg'.format(attributes['datetime']))
    pl.xlim((-128, 128))
    pl.ylim((-128, 128))

    pl.savefig('/home/luke/stationradar_viewer/fbg_latest.png', dpi=(300), bbox_inches='tight')
    pl.close(None)

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        load_radar_data()
  
        # Pixmap LEFT
        pixmap_left = QPixmap('/home/luke/stationradar_viewer/tur_latest.png')
        pixmap_left = pixmap_left.scaled(900, 1080, Qt.KeepAspectRatio)
        # Pixmap RIGHT
        pixmap_right = QPixmap('/home/luke/stationradar_viewer/fbg_latest.png')
        pixmap_right = pixmap_right.scaled(900, 1080, Qt.KeepAspectRatio)

        # LEFT Map
        left_map = QLabel(self)
        left_map.setPixmap(pixmap_left)
        left_map.setAlignment(Qt.AlignLeft)
        # RIGHT Map
        right_map = QLabel(self)
        right_map.setPixmap(pixmap_right)
        right_map.setAlignment(Qt.AlignLeft)

        main_container = QVBoxLayout()

        map_container = QHBoxLayout()
        map_container.addWidget(left_map)
        map_container.addWidget(right_map)
  
        self.setLayout(map_container)
        self.setGeometry(0, 0, 1920, 1080)
        self.setWindowTitle('Stationradar Viewer')
    
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    app.quit
    sys.exit(app.exec_())

Screenshot of all Windows

1 Answers

The problem is that plt.ion() enables interactive mode making windows remain open. And why did the window close when Qt was not used? I'm assuming (because you don't provide any code for that case) that the matplotlib eventloop allowed the instructions to run or the application closed so quickly that the phenomenon was not observed.

The solution is to remove that command, also for easy path management I have modified your code to:

import os
import sys

import numpy as np
import matplotlib.pyplot as plt
import wradlib
import warnings

warnings.filterwarnings("ignore")

import requests

from PyQt5.QtWidgets import QApplication, QHBoxLayout, QLabel, QVBoxLayout, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt


viewer_dir = "/home/luke/stationradar_viewer"

# Setting environment Variable
os.environ["WRADLIB_DATA"] = viewer_dir


def load_radar_data():
    try:
        get_ipython().magic("matplotlib inline")
    except:
        pass
        # plt.ion()

    RADAR_URL = "https://opendata.dwd.de/weather/radar/sites/dx/tur/raa00-dx_10832-latest-tur---bin"
    r = requests.get(RADAR_URL)

    with open(os.path.join(viewer_dir, "raa00-dx_10832-latest-tur---bin"), "wb") as f:
        f.write(r.content)

    filename = wradlib.util.get_wradlib_data_file("raa00-dx_10832-latest-tur---bin")

    one_scan, attributes = wradlib.io.read_dx(filename)

    plt.figure(figsize=(10, 8))
    ax, pm = wradlib.vis.plot_ppi(one_scan)
    ax = wradlib.vis.plot_ppi_crosshair((0, 0, 0), ranges=[40, 80, 128])

    cbar = plt.colorbar(pm, shrink=0.9)
    cbar.set_label("Reflectivity (dBZ)")

    plt.title("Reflectivity at {0}\nDWD radar Türkheim".format(attributes["datetime"]))
    plt.xlim((-128, 128))
    plt.ylim((-128, 128))

    plt.savefig(
        os.path.join(viewer_dir, "tur_latest.png"), dpi=(300), bbox_inches="tight"
    )

    ########

    RADAR_URL = "https://opendata.dwd.de/weather/radar/sites/dx/fbg/raa00-dx_10908-latest-fbg---bin"
    r = requests.get(RADAR_URL)

    with open(os.path.join(viewer_dir, "raa00-dx_10908-latest-fbg---bin"), "wb") as f:
        f.write(r.content)

    filename = wradlib.util.get_wradlib_data_file("raa00-dx_10908-latest-fbg---bin")

    one_scan, attributes = wradlib.io.read_dx(filename)

    plt.figure(figsize=(10, 8))
    ax, pm = wradlib.vis.plot_ppi(one_scan)
    ax = wradlib.vis.plot_ppi_crosshair((0, 0, 0), ranges=[40, 80, 128])

    cbar = plt.colorbar(pm, shrink=0.9)
    cbar.set_label("Reflectivity (dBZ)")

    plt.title("Reflectivity at {0}\nDWD radar Feldberg".format(attributes["datetime"]))
    plt.xlim((-128, 128))
    plt.ylim((-128, 128))

    plt.savefig(
        os.path.join(viewer_dir, "fbg_latest.png"), dpi=(300), bbox_inches="tight"
    )


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        load_radar_data()

        # Pixmap LEFT
        pixmap_left = QPixmap(os.path.join(viewer_dir, "tur_latest.png"))
        pixmap_left = pixmap_left.scaled(900, 1080, Qt.KeepAspectRatio)
        # Pixmap RIGHT
        pixmap_right = QPixmap(os.path.join(viewer_dir, "fbg_latest.png"))
        pixmap_right = pixmap_right.scaled(900, 1080, Qt.KeepAspectRatio)

        # LEFT Map
        left_map = QLabel(self)
        left_map.setPixmap(pixmap_left)
        left_map.setAlignment(Qt.AlignLeft)
        # RIGHT Map
        right_map = QLabel(self)
        right_map.setPixmap(pixmap_right)
        right_map.setAlignment(Qt.AlignLeft)

        main_container = QVBoxLayout()

        map_container = QHBoxLayout()
        map_container.addWidget(left_map)
        map_container.addWidget(right_map)

        self.setLayout(map_container)
        self.setGeometry(0, 0, 1920, 1080)
        self.setWindowTitle("Stationradar Viewer")

        self.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    app.quit
    sys.exit(app.exec_())
Related