无法使用Qt5Agg后端渲染matplotlib图形

5

我试图让这个脚本工作,但是每当我在终端运行它时,即使脚本仍在运行,它也不会渲染。

我使用以下命令安装了Qt5Agg:

pip install Qt5Agg 

我正在使用一台Windows 10电脑。
我使用的是Python 3.5版本。
在终端中没有出现任何错误提示。
我已经安装了脚本所需的所有依赖项。

以下是脚本内容:

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)
1个回答

15

首先,我假设您已经安装了 PyQt5,因为没有 Qt5Agg

您不应该使用 plt.switch_backend, 您可以在这里快速查看文档 (http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.switch_backend)。

更改您的导入语句,如下所示,因为在导入 pyplot 后无法更改后端:

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

这对我来说不成功。 - Youssri Abo Elseod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接