【问题标题】:getting error when plotting with matplotlib使用 matplotlib 绘图时出错
【发布时间】:2018-08-24 10:41:39
【问题描述】:

我正在尝试使用 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)

有什么问题?

【问题讨论】:

  • 能否修正一下错误信息的格式?
  • 您可以将fig.add_subplot(1,1,axisbg="black") 替换为fig.add_subplot(111,axisbg="black")。

标签: python matplotlib python-3.7


【解决方案1】:

问题在于add_subplot 有三个 强制参数,而不是两个。参数是 M =“行数”、N =“列数”和 P =“项目选择”。最后一个 (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()   

【讨论】:

  • 它现在给了我错误:未知属性axisbg
  • @ElizaRomanski。在 matplotlib 2.0.0 中不推荐使用 axis_bg axis_bgcolor 并在 matplotlib 2.2.0 中删除。将立即更新。
  • @ElizaRomanski 因为它只接受某些关键字参数,as per docs: **kwargs 这个方法也接受 Axes 的关键字参数。
【解决方案2】:

来自matplotlib docs:

add_subplot(*args, **kwargs)[来源]

添加一个子图。

调用签名:

add_subplot(nrows, ncols, index, **kwargs)

add_subplot(pos, **kwargs)

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

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2020-12-27
    • 2019-04-22
    • 2018-02-22
    • 1970-01-01
    • 2020-09-26
    • 2019-06-29
    • 2018-09-07
    相关资源
    最近更新 更多