使用matplotlib绘图时出现错误

时间:2018-08-24 10:41:40

标签: python matplotlib python-3.7

我正在尝试在python 3.7中使用matplotlib进行绘图。

这是我的代码:

import matplotlib
fig = matplotlib.pyplot.figure()
rect = fig.patch
rect.set_facecolor("green")
x = [3, 7, 8, 12]
y = [5, 13, 2, 8]
graph1 = fig.add_subplot(1, 1, axisbg="black")
graph1.plot(x, y, "red", linewidth=4.0)
matplotlib.pyplot.show()   

但是我一直收到此错误:

File "C:\Users\User\Anaconda3\lib\site-packages\matplotlib\axes\_subplots.py", line 72, in __init__
  raise ValueError('Illegal argument(s) to subplot: %s' % (args,))

ValueError: Illegal argument(s) to subplot: (1, 1)

出什么问题了?

2 个答案:

答案 0 :(得分:2)

问题在于add_subplot具有三个强制性参数,而不是两个。参数为M =“行数”,N =“列数”和P =“项目选择”。最后一个(P)是MxN网格中的线性索引。

此外,在matplotlib 2.0.0中不推荐使用axis_bgaxis_bgcolor参数,在matplotlib 2.2.0中将其删除。请改用facecolorfc

您可能想做

graph1 = fig.add_subplot(1, 1, 1, fc="black")

话虽如此,如果您想在一个图形上创建一组轴,我通常发现更容易使用plt.subplots一次绘制图形和轴:

fig, graph1 = plt.subplots(subplot_kw={'facecolor': 'black'}, facecolor='green')

为方便起见,最常见的做法是将pyplot导入为plt,或者使用

import matplotlib.pyplot as plt

或搭配

from matplotlib import pyplot as plt

综合起来,您的代码可能最终看起来像这样:

from matplotlib import pyplot as plt

fig, graph1 = plt.subplots(subplot_kw={'facecolor': 'black'},
                           facecolor='green')

x = [3, 7, 8, 12]
y = [5, 13, 2, 8]
graph1.plot(x, y, "red", linewidth=4.0)
plt.show()   

答案 1 :(得分:0)

来自matplotlib docs

  

add_subplot(* args,** kwargs)[source]

     

添加子图。

     

通话签名:

     

add_subplot(行数,ncol,索引,** kwargs)

     

add_subplot(pos,** kwargs)

据我所知,您没有为函数提供index参数。

相关问题