首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python 3 matplotlib不支持生成器作为输入。

Python 3 matplotlib不支持生成器作为输入。
EN

Stack Overflow用户
提问于 2022-06-21 20:13:50
回答 1查看 176关注 0票数 0

我对Python相当陌生,我花了几个小时才弄明白我能做什么却没有成功。我正在尝试一个从https://jupyter.brynmawr.edu/services/public/dblank/jupyter.cs/FLAIRS-2015/TSPv3.ipynb#Python-and-iPython-Notebook:-Preliminaries绘图的例子。在“绘图旅游”一节,标记为15,16,17,18等单元。plot_tour和plot_lines的函数使用map(),我在Python3中看到它是一个生成器,而不是一个列表。这让人感到困惑,所以有没有其他方法可以输出这个情节呢?它可能不使用map()。提前谢谢你。

第一个绘图代码:

代码语言:javascript
运行
复制
def plot_tour(tour): 
    "Plot the cities as circles and the tour as lines between them."
    plot_lines(list(tour) + [tour[0]])
    
def plot_lines(points, style='bo-'):
    "Plot lines to connect a series of points."
    plt.plot(map(X, points), map(Y, points), style)
    plt.axis('scaled'); plt.axis('off')
plot_tour(alltours_tsp(Cities(8)))

这是我得到的错误:

代码语言:javascript
运行
复制
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Input In [18], in <cell line: 1>()
----> 1 plot_tour(alltours_tsp(Cities(8)))

Input In [17], in plot_tour(tour)
      1 def plot_tour(tour): 
      2     "Plot the cities as circles and the tour as lines between them."
----> 3     plot_lines(list(tour) + [tour[0]])

Input In [17], in plot_lines(points, style)
      5 def plot_lines(points, style='bo-'):
      6     "Plot lines to connect a series of points."
----> 7     plt.plot(map(X, points), map(Y, points), style)
      8     plt.axis('scaled'); plt.axis('off')

File ~\anaconda3\lib\site-packages\matplotlib\pyplot.py:2757, in plot(scalex, scaley, data, *args, **kwargs)
   2755 @_copy_docstring_and_deprecators(Axes.plot)
   2756 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2757     return gca().plot(
   2758         *args, scalex=scalex, scaley=scaley,
   2759         **({"data": data} if data is not None else {}), **kwargs)

File ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py:1632, in Axes.plot(self, scalex, scaley, data, *args, **kwargs)
   1390 """
   1391 Plot y versus x as lines and/or markers.
   1392 
   (...)
   1629 (``'green'``) or hex strings (``'#008000'``).
   1630 """
   1631 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1632 lines = [*self._get_lines(*args, data=data, **kwargs)]
   1633 for line in lines:
   1634     self.add_line(line)

File ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py:312, in _process_plot_var_args.__call__(self, data, *args, **kwargs)
    310     this += args[0],
    311     args = args[1:]
--> 312 yield from self._plot_args(this, kwargs)

File ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py:493, in _process_plot_var_args._plot_args(self, tup, kwargs, return_kwargs)
    490     x, y = index_of(xy[-1])
    492 if self.axes.xaxis is not None:
--> 493     self.axes.xaxis.update_units(x)
    494 if self.axes.yaxis is not None:
    495     self.axes.yaxis.update_units(y)

File ~\anaconda3\lib\site-packages\matplotlib\axis.py:1443, in Axis.update_units(self, data)
   1437 def update_units(self, data):
   1438     """
   1439     Introspect *data* for units converter and update the
   1440     axis.converter instance if necessary. Return *True*
   1441     if *data* is registered for unit conversion.
   1442     """
-> 1443     converter = munits.registry.get_converter(data)
   1444     if converter is None:
   1445         return False

File ~\anaconda3\lib\site-packages\matplotlib\units.py:206, in Registry.get_converter(self, x)
    202 else:
    203     # ... and avoid infinite recursion for pathological iterables for
    204     # which indexing returns instances of the same iterable class.
    205     if type(first) is not type(x):
--> 206         return self.get_converter(first)
    207 return None

File ~\anaconda3\lib\site-packages\matplotlib\units.py:199, in Registry.get_converter(self, x)
    197         pass
    198 try:  # If cache lookup fails, look up based on first element...
--> 199     first = cbook.safe_first_element(x)
    200 except (TypeError, StopIteration):
    201     pass

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:1678, in safe_first_element(obj)
   1676     except TypeError:
   1677         pass
-> 1678     raise RuntimeError("matplotlib does not support generators "
   1679                        "as input")
   1680 return next(iter(obj))

RuntimeError: matplotlib does not support generators as input

下一个情节代码:

代码语言:javascript
运行
复制
def plot_tsp(algorithm, cities):
    "Apply a TSP algorithm to cities, plot the resulting tour, and print information."
    # Find the solution and time how long it takes
    t0 = time.clock()
    tour = algorithm(cities)
    t1 = time.clock()
    assert valid_tour(tour, cities)
    plot_tour(tour); plt.show()
    print("{} city tour with length {:.1f} in {:.3f} secs for {}"
          .format(len(tour), tour_length(tour), t1 - t0, algorithm.__name__))
    
def valid_tour(tour, cities):
    "Is tour a valid tour for these cities?"
    return set(tour) == set(cities) and len(tour) == len(cities)
plot_tsp(alltours_tsp, Cities(8))

这是我得到的错误:

代码语言:javascript
运行
复制
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Input In [23], in <cell line: 1>()
----> 1 plot_tsp(alltours_tsp, Cities(8))

Input In [22], in plot_tsp(algorithm, cities)
      6 t1 = time.perf_counter()
      7 assert valid_tour(tour, cities)
----> 8 plot_tour(tour); plt.show()
      9 print("{} city tour with length {:.1f} in {:.3f} secs for {}"
     10       .format(len(tour), tour_length(tour), t1 - t0, algorithm.__name__))

Input In [17], in plot_tour(tour)
      1 def plot_tour(tour): 
      2     "Plot the cities as circles and the tour as lines between them."
----> 3     plot_lines(list(tour) + [tour[0]])

Input In [17], in plot_lines(points, style)
      5 def plot_lines(points, style='bo-'):
      6     "Plot lines to connect a series of points."
----> 7     plt.plot(map(X, points), map(Y, points), style)
      8     plt.axis('scaled'); plt.axis('off')

File ~\anaconda3\lib\site-packages\matplotlib\pyplot.py:2757, in plot(scalex, scaley, data, *args, **kwargs)
   2755 @_copy_docstring_and_deprecators(Axes.plot)
   2756 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2757     return gca().plot(
   2758         *args, scalex=scalex, scaley=scaley,
   2759         **({"data": data} if data is not None else {}), **kwargs)

File ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py:1632, in Axes.plot(self, scalex, scaley, data, *args, **kwargs)
   1390 """
   1391 Plot y versus x as lines and/or markers.
   1392 
   (...)
   1629 (``'green'``) or hex strings (``'#008000'``).
   1630 """
   1631 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1632 lines = [*self._get_lines(*args, data=data, **kwargs)]
   1633 for line in lines:
   1634     self.add_line(line)

File ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py:312, in _process_plot_var_args.__call__(self, data, *args, **kwargs)
    310     this += args[0],
    311     args = args[1:]
--> 312 yield from self._plot_args(this, kwargs)

File ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py:493, in _process_plot_var_args._plot_args(self, tup, kwargs, return_kwargs)
    490     x, y = index_of(xy[-1])
    492 if self.axes.xaxis is not None:
--> 493     self.axes.xaxis.update_units(x)
    494 if self.axes.yaxis is not None:
    495     self.axes.yaxis.update_units(y)

File ~\anaconda3\lib\site-packages\matplotlib\axis.py:1443, in Axis.update_units(self, data)
   1437 def update_units(self, data):
   1438     """
   1439     Introspect *data* for units converter and update the
   1440     axis.converter instance if necessary. Return *True*
   1441     if *data* is registered for unit conversion.
   1442     """
-> 1443     converter = munits.registry.get_converter(data)
   1444     if converter is None:
   1445         return False

File ~\anaconda3\lib\site-packages\matplotlib\units.py:206, in Registry.get_converter(self, x)
    202 else:
    203     # ... and avoid infinite recursion for pathological iterables for
    204     # which indexing returns instances of the same iterable class.
    205     if type(first) is not type(x):
--> 206         return self.get_converter(first)
    207 return None

File ~\anaconda3\lib\site-packages\matplotlib\units.py:199, in Registry.get_converter(self, x)
    197         pass
    198 try:  # If cache lookup fails, look up based on first element...
--> 199     first = cbook.safe_first_element(x)
    200 except (TypeError, StopIteration):
    201     pass

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:1678, in safe_first_element(obj)
   1676     except TypeError:
   1677         pass
-> 1678     raise RuntimeError("matplotlib does not support generators "
   1679                        "as input")
   1680 return next(iter(obj))

RuntimeError: matplotlib does not support generators as input
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-21 20:38:34

我怀疑这个笔记本是为早期版本的python和软件包制作的。所以你才有这么多问题。我建议跟踪本课程中使用的python和包版本的一些规范。然而,我确实得到了大量的笔记本电脑运行这些变化:

代码语言:javascript
运行
复制
def plot_lines(points, style='bo-'):
    "Plot lines to connect a series of points."
    plt.plot(list(map(X, points)), list(map(Y, points)), style)
    plt.axis('scaled'); plt.axis('off')

稍后,应该将time.time()替换为perf_counter()

代码语言:javascript
运行
复制
def plot_tsp(algorithm, cities):
    "Apply a TSP algorithm to cities, plot the resulting tour, and print information."
    # Find the solution and time how long it takes
    t0 = time.perf_counter()
    tour = algorithm(cities)
    t1 = time.perf_counter()
    assert valid_tour(tour, cities)
    plot_tour(tour); plt.show()
    print("{} city tour with length {:.1f} in {:.3f} secs for {}"
          .format(len(tour), tour_length(tour), t1 - t0, algorithm.__name__))
代码语言:javascript
运行
复制
def benchmark(function, inputs):
    "Run function on all the inputs; return pair of (average_time_taken, results)."
    t0           = time.perf_counter()
    results      = map(function, inputs)
    t1           = time.perf_counter()
    average_time = (t1 - t0) / len(inputs)
    return (average_time, results)

然而,还有一些其他的改变需要在笔记本上做进一步的修改。benchmark函数和USA big map url请求有问题。不过,您确实应该考虑挖掘包版本。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72706616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档