Matplotlib绘图生成器 [英] Matplotlib plotting generators

查看:175
本文介绍了Matplotlib绘图生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它在我执行时(在Python 3中)绘制:

import matplotlib.pyplot as plt

a = [1,2,3,4,5]

plt.plot(range(5), a)
plt.show()

据我所知,在Python 3中,range()返回一个迭代器,因此我上面的代码在一个迭代器上进行了很多绘制.现在我的问题是,为什么我不能这样做:

def myGen(iterable):
    for i in iterable:
        yield i
a = myGen([1,2,3,4,5])
plt.plot(range(5),a)
plt.show()

尝试此操作时,我得到ValueError: x and y must have same first dimension

考虑它时,想要绘制两个生成器是很有意义的.只是逐点绘制.在matplotlib中可以吗?

我知道有一个类似的线索,很遗憾没有得到答复.

解决方案

问题是,即使Python 3中的range不是真实列表,它仍然提供了比自定义生成器更多的功能.特别是,它提供了__len__.这是至关重要的,因为matplotlib将所有内容都转换为底层的numpy数组,并且numpy数组要求其大小预先知道. Python 3范围对象还提供项目访问,因此它们实际上非常类似于普通序列.您可以在文档中看到它们不是简单的生成器. >

我不确定要使自己的自定义类在这里工作所需要做的全部工作,但这可能比它的价值还要麻烦. Matplotlib需要能够将您的数据转换为numpy数组,而numpy又需要比简单的此对象可迭代"更多的信息.它需要能够知道有多少数据并立即获得所有数据.

It plots when I do (in Python 3):

import matplotlib.pyplot as plt

a = [1,2,3,4,5]

plt.plot(range(5), a)
plt.show()

As far as I know, in Python 3, range() returns an iterator so my code above pretty much plots over an iterator. Now my question is, why am I not able to do:

def myGen(iterable):
    for i in iterable:
        yield i
a = myGen([1,2,3,4,5])
plt.plot(range(5),a)
plt.show()

When I try this, I get ValueError: x and y must have same first dimension

When you think about it, it makes sense wanting to plot over two generators. Just plot point after point. Is this possible in matplotlib?

I am aware that there is a similar thread, unfortunately unanswered.

解决方案

The thing is that even though range in Python 3 is not a real list, it still provides a lot more functionality than your custom generator. In particular, it provides __len__. This is crucial because matplotlib converts everything to numpy arrays under the hood, and numpy arrays requre their size to be known up front. Python 3 range objects also provide item access, so they really are pretty much like ordinary sequences. You can see in the documentation that they are not simple generators.

I'm not sure exactly what all you'd need to do to make your own custom class work here, but it's probably more trouble than it's worth. Matplotlib needs to be able to convert your data into a numpy array, and numpy in turn needs much more information than simple "this object is iterable". It needs to be able to know how much data there is and get it all at once.

这篇关于Matplotlib绘图生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆