使用 matplotlib 绘图时出现错误
getting error when plotting with matplotlib
我正在尝试使用 matplotlib 和 python 3.7.
进行绘图
这是我的代码:
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)
有什么问题?
来自 matplotlib docs:
add_subplot(*args, **kwargs)[source]
Add a subplot.
Call signatures:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
据我所知,您没有为函数提供 index
参数。
问题是 add_subplot
有 三个 个强制参数,而不是两个。参数是 M = "number of rows"、N = "number of columns" 和 P = "item selection"。最后一个(P)是MxN网格中的线性索引,跨越
此外,axis_bg
和 axis_bgcolor
参数在 matplotlib 2.0.0 中已弃用,并在 matplotlib 2.2.0 中删除。相反,请使用 facecolor
或 fc
简称。
你可能想做
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()
我正在尝试使用 matplotlib 和 python 3.7.
进行绘图这是我的代码:
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)
有什么问题?
来自 matplotlib docs:
add_subplot(*args, **kwargs)[source]
Add a subplot.
Call signatures:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
据我所知,您没有为函数提供 index
参数。
问题是 add_subplot
有 三个 个强制参数,而不是两个。参数是 M = "number of rows"、N = "number of columns" 和 P = "item selection"。最后一个(P)是MxN网格中的线性索引,跨越
此外,axis_bg
和 axis_bgcolor
参数在 matplotlib 2.0.0 中已弃用,并在 matplotlib 2.2.0 中删除。相反,请使用 facecolor
或 fc
简称。
你可能想做
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()