plot is not defined

前端 未结 2 1912
醉酒成梦
醉酒成梦 2021-02-07 07:46

I started to use matplotlib library to get a graph. But when I use \"plot(x,y)\" it returns me that \"plot is not defined\".

To import , I used the following command:

相关标签:
2条回答
  • 2021-02-07 08:19

    If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:

    import matplotlib.pyplot
    matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
    matplotlib.pyplot.show()
    

    In your solution

    from matplotlib import*
    

    This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as

    from matplotlib.pyplot import *
    plot([1,2,3,4,5],[5,4,3,2,1],"bx")
    show()
    

    Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.

    I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:

    import matplotlib.pyplot as plt
    plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
    plt.show()
    
    0 讨论(0)
  • 2021-02-07 08:32

    Change that import to

    from matplotlib.pyplot import *
    

    Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

    import matplotlib.pyplot as plt
    plt.plot([1,2,3,4])
    
    0 讨论(0)
提交回复
热议问题