Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't render a matplotlib graph using Qt5Agg backend

I'm trying to make this script work, but whenever I run it in the terminal, it doesn't render even if the script is still running.

I installed Qt5Agg using

pip install Qt5Agg 

I'm on a windows 10 computer.
I use python 3.5
I've got no error in the terminal.
I've got all the needed dependencies for the script.

Here is the script:

import csv
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt


plt.switch_backend('Qt5Agg')



dates = []
prices = []

def get_data(filename):
    with open(filename, 'r') as csvfile:
        csvFileReader = csv.reader(csvfile)
        next(csvFileReader) # skipping column names
        for row in csvFileReader:
            dates.append(int(row[0].split('-')[0]))
            prices.append(float(row[1]))
    return

def predict_price(dates, prices, x):
    dates = np.reshape(dates,(len(dates), 1)) # converting to matrix of n X 1

    svr_lin = SVR(kernel= 'linear', C= 1e3)
    svr_poly = SVR(kernel= 'poly', C= 1e3, degree= 2)
    svr_rbf = SVR(kernel= 'rbf', C= 1e3, gamma= 0.1) # defining the support vector regression models
    svr_rbf.fit(dates, prices) # fitting the data points in the models
    svr_lin.fit(dates, prices)
    svr_poly.fit(dates, prices)

    plt.scatter(dates, prices, color= 'black', label= 'Data') # plotting the initial datapoints
    plt.plot(dates, svr_rbf.predict(dates), color= 'red', label= 'RBF model') # plotting the line made by the RBF kernel
    plt.plot(dates,svr_lin.predict(dates), color= 'green', label= 'Linear model') # plotting the line made by linear kernel
    plt.plot(dates,svr_poly.predict(dates), color= 'blue', label= 'Polynomial model') # plotting the line made by polynomial kernel
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('Support Vector Regression')
    plt.legend()
    plt.show()

    return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0]

get_data('deutch.csv') # calling get_data method by passing the csv file to it
#print "Dates- ", dates
#print "Prices- ", prices

predicted_price = predict_price(dates, prices, 40)

print(predicted_price)
like image 932
EZPK Avatar asked Dec 25 '22 00:12

EZPK


1 Answers

First of all, I presume that you installed PyQt5, as there is no Qt5Agg.

You should not use plt.switch_backend, you can have a quick look at the documentation here (http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.switch_backend).

Change your import statement like this as it is not possible to change the backend after importing pyplot:

import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
like image 186
oschoudhury Avatar answered Jan 13 '23 02:01

oschoudhury