简体   繁体   English

matplotlib.pyplot.plot()不显示图形

[英]matplotlib.pyplot.plot() doesn't show the graph

I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. 我正在学习Python,并且有一个辅助项目可以学习使用matplotlib.pyplot模块显示数据。 Here is an example to display the data using dates[] and prices[] as data. 这是一个使用date []和price []作为数据显示数据的示例。 Does anyone know why we need line 5 and line 6? 有谁知道为什么我们需要第5行和第6行? I am confused why this step is needed to have the graph displayed. 我很困惑为什么需要此步骤才能显示图形。

from sklearn import linear_model
import matplotlib.pyplot as plt

def showgraph(dates, prices):
  dates  = numpy.reshape(dates, (len(dates), 1))   # line 5
  prices = numpy.reshape(prices, (len(prices), 1)) # line 6

  linear_mod = linear_model.LinearRegression()
  linear_mod.fit(dates,prices)
  plt.scatter(dates,prices,color='yellow') 
  plt.plot(dates,linear_mod.predict(dates),color='green')
  plt.show()

try the following in terminal to check the backend: 在终端中尝试以下操作以检查后端:

import matplotlib
import matplotlib.pyplot
print matplotlib.backends.backend

If it shows 'agg', it is a non-interactive one and wont show but plt.savefig works. 如果显示“ agg”,则它是非交互式的,不会显示,但plt.savefig有效。

To show the plot, you need to switch to TkAgg or Qt4Agg. 要显示该图,您需要切换到TkAgg或Qt4Agg。

You need to edit the backend in matplotlibrc file. 您需要在matplotlibrc文件中编辑后端。 To print its location in terminal do the following. 要在终端中打印其位置,请执行以下操作。

import matplotlib
matplotlib.matplotlib_fname()

more about matplotlibrc 有关matplotlibrc的更多信息

Line 5 and 6 transform what Im assuming are row vectors (im not sure how data and prices are encoded before this transformation) into column vectors. 第5行和第6行将Im假定的行向量(不确定在此转换之前如何编码dataprices )转换为列向量。 So now you have vectors that look like this. 所以现在您有了矢量,如下所示。

[0,
 1, 
 2, 
 3]

which is the form that linear_model.Linear_Regression.fit() is expecting. 这是linear_model.Linear_Regression.fit()期望的形式。 The reshaping was not necessary for plotting under the assumption that data and prices are row vectors. 在数据和价格是行向量的假设下,重塑对于绘图来说是不必要的。

My approach is exactly like yours but still without line 5 and 6 display is correct. 我的方法与您的方法完全一样,但是仍然没有显示第5行和第6行。 I think those line are unnecessary. 我认为这些行是不必要的。 It seems that you do not need fit() function because of your input data are in row format. 似乎您不需要fit()函数,因为您的输入数据为行格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM