【问题标题】:Graph wont show in Python图表不会在 Python 中显示
【发布时间】:2019-05-13 19:02:59
【问题描述】:

我是编程新手,我正在尝试让图形在 Python 中工作。但我遇到了某种错误,图表不会显示。我在 Ubuntu 操作系统上。希望一些 Python 大师可以解释什么是错误的以及如何解决它。

代码:

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



dates = []
prices = []

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

 def predict_prices(dates, prices, x):
    dates = np.reshape(dates,(len(dates), 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)
    svr_rbf.fit(dates, prices)
    svr_poly.fit(dates, prices)
    svr_rbf.fit(dates, prices)

    plt.scatter(dates, prices, color='black', label='Data')
    plt.plot(dates, svr_rbf.predict(dates), color='red', label='RBF model')
    plt.plot(dates, svr_lin.predict(dates), color='green', label='Linear 
model')
    plt.plot(dates, svr_poly.predict(dates), color='blue', label='Polynomial 
model')
    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('aapl.csv')
predicted_price = predict_prices(dates, prices, 29)
print(predicted_price)

导致此错误:

/home/xxx/.local/lib/python3.6/site-packages/sklearn/svm/base.py:196:
FutureWarning:在 0.22 版本中,gamma 的默认值将从“auto”更改为“scale”,以更好地考虑未缩放的功能。将 gamma 显式设置为“auto”或“scale”以避免出现此警告。

【问题讨论】:

  • 您上面显示的“错误”实际上是来自 sklearn 的警告。它不会以任何方式影响您的代码的工作。未显示的图完全是一个不同的错误。显示带有数据样本的完整代码,以便我们可以尝试重现它。还显示有关您的系统、操作系统、库版本的详细信息可能会有所帮助/

标签: python numpy matplotlib scikit-learn


【解决方案1】:

我曾经遇到过这种情况,即情节没有出现。就我而言,它与 matplotlib 使用的后端有关。

要检查选定的后端,您可以试试这个:

 matplotlib.get_backend()

使用 matplotlib 作为默认后端的典型安装通常已经设置,但根据您的操作系统和您的特定用例,您可能需要选择不同的设置。

例如,在我当前在 ubuntu 18.04 上的安装中,我使用的是“Qt5Agg”后端。

您始终可以在此处的官方文档中找到更多信息:https://matplotlib.org/faq/usage_faq.html#what-is-a-backend

复制以上链接:

有四种方法可以配置您的后端。如果它们相互冲突 其他,将使用以下列表中最后提到的方法, 例如调用 use() 将覆盖 matplotlibrc 中的设置。

你的 matplotlibrc 文件中的后端参数

backend : WXAgg   # use wxpython with antigrain (agg) rendering

为当前的 shell 或单个脚本设置 MPLBACKEND 环境变量:

export MPLBACKEND="module://my_backend"
python simple_plot.py

MPLBACKEND="module://my_backend" python simple_plot.py

要为单个脚本设置后端,您也可以使用 -d 命令行参数(已弃用):

python script.py -dbackend

如果您的脚本依赖于特定的后端,您可以使用 use() 函数:

import matplotlib
matplotlib.use('PS') 

【讨论】:

  • "TkAgg" 我应该在代码中添加什么使其工作?
猜你喜欢
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 2021-03-07
  • 1970-01-01
  • 2021-09-27
  • 2021-07-18
  • 2013-12-08
  • 2012-12-25
相关资源
最近更新 更多