简体   繁体   English

绘制基本矢量化函数

[英]Plotting a basic vectorized function

I am trying to get my function to plot a vectorized function over a python list interval and having a name / title for the graph. 我正在尝试让我的函数在python列表间隔上绘制矢量化函数,并为图形提供name / title I am fairly new to python packages like numpy and matplotlib. 我对numpy和matplotlib之类的python包是相当陌生的。 I hope someone can shed some light on my code: 我希望有人可以阐明我的代码:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline    

def test_plot(x,interval,title):
    x = np.vectorize(x)
    interval = [0,interval+1]
    ttl = plt.title(title)
    plt.plot(x,interval)
    return plt.plot(x,interval)    

test_plot([-1,0,1,2,3,4],2,'test')

I get this error: 我收到此错误:

ValueError: x and y must have same first dimension

Note: I need the interval to be a list . 注意:我需要将interval设为list

I don't quite understand what you are going to plot. 我不太明白你要画什么。

After checking the document , you can find : 检查文档后,您可以找到:

numpy.vectorize requires a pyfunc to be initialized . numpy.vectorize需要初始化pyfunc。

For example : 例如 :

>>> def myfunc(a, b):
...     "Return a-b if a>b, otherwise return a+b"
...     if a > b:
...         return a - b
...     else:
...         return a + b

Then initiate your vectorize function 然后启动您的矢量化功能

>>>vfunc = np.vectorize(myfunc)
>>>vfunc([1, 2, 3, 4], 2)
array([3, 4, 1, 2])

The parameter pyfunc must be callable . 参数pyfunc必须是可调用的 Passing a list seems meaningless . 通过清单似乎毫无意义。

As for matplotlib.pyplot.plot . 至于matplotlib.pyplot.plot

This function require x and y to have same dimension to be plotted . 此函数要求x和y具有相同的绘制尺寸。

But what your pass is a function and two elements list causing a ValueError 但是您传递的是一个函数和两个元素列表,导致ValueError

Like KIDJournety, I don't quite understand what you're wanting either, but if I understand your comments correctly this might work: 像KIDJournety一样,我也不太了解您想要什么,但是如果我正确理解您的评论,这可能会起作用:

def test_plot(x, interval, title): import matplotlib.pyplot as plt plt.title(title) plt.plot(x, interval) plt.show()

test_plot([1,2,3], [7,6,5], "hello, world!") works well. test_plot([1,2,3], [7,6,5], "hello, world!")工作正常。 If this doesn't do what you need (what with the vectorisation) please comment below and I'll do my best to adjust the code accordingly. 如果这不能满足您的需求(向量化的用途),请在下面发表评论,我会尽力相应地调整代码。

Now for some practical reasons why your original code did not work: You were passing a list or vector with 6 elements (-1 through 4) as the x-values of the graph, but only 2 elements(0 and interval+1, which was 3 in your example) as your y-values. 现在出于某些实际原因,您的原始代码为何不起作用:您传递的列表或向量具有6个元素(-1至4)作为图形的x值,但只有2个元素(0和interval + 1,其中在您的示例中为3)作为y值。 Your poor code could only pair (-1, 0) and (0,3). 您的不良代码只能配对(-1,0)和(0,3)。 The rest of the x-coordinates had no corresponding y-coordinates to be paired to, so the code failed. 其余的x坐标没有要配对的相应y坐标,因此代码失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM