简体   繁体   中英

Matplotlib error "x and y must have same first dimension, but have shapes (1,) and (6,)"

I'm trying to make a graph as proof of convergence of geometric series. This is my code:

import matplotlib.pyplot as graph

def cv12(nula,r,n):  # nula is A0 (first term), r is common ratio and n is how many terms we want
    sucet=0          # sum of series
    a=nula           # assign A0 as current term
    konvergencia=nula/(1-r) 
    x=[sucet]
    y=[a]
    for i in range(n):
        sucet=sucet+a
        x.append(sucet)
        print(sucet)
        a=a*r
        y.append(a)
    graph.plot(x,y,label="Geometrický rad")
    graph.plot(konvergencia,y)
    
cv12(1,2,5)

but I get this error

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 399, in _plot_args
    raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (1,) and (6,)

graph.plot(konvergencia,y) is the problem. konvergencia is just a float variable, while y is a list. they have to match because plt.plot() just draws points at (xi, yi) what do you want to plot there? if you want to draw a line with x=konvergencia then do this:

graph.plot(len(y)*[konvergencia],y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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