Ravi Teja Gudapati
Ravi Teja Gudapati

Reputation: 2869

Matplotlib: What does calling plot function with an array do?

What does calling plot function with an array for both x and y do? Look at line number 15.

x1 = stats.norm.ppf(0.001)
x2 = stats.norm.ppf(0.999)

x = np.linspace(x1, x2, 100)

y = stats.norm.pdf(x)

yhalf = []
for i in range(len(x)):
    if i > len(x)/2:
        yhalf.append(y[i])
    else:
        yhalf.append(0)

plt.plot([x, x], [y, yhalf], 'y-')

plt.axes().set_xlim(x1, x2)

Plot

Does it fill the area between two curves? Can we control or style this filling? I would like to fill with a smooth color with transparency.

Thanks!

Upvotes: 1

Views: 63

Answers (1)

pingul
pingul

Reputation: 3473

From the docs:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

That is, if we have a, b, c, d all np.arrays with the same size s, the command plt.plot([a, b], [c, d]) will plot s number of lines (a[0], c[0]) -> (b[0], d[0]).

In your case yhalf[0:len(x)/2] is 0, and the other values are the same as y. From what I said before, you draw lines from (x[i], y[i]) -> (x[i], yhalf[i]), which for

case 1: i <  len(x)/2: (x[i], y[i]) -> (x[i], 0)    <-- the columns you see
case 2: i >= len(x)/2: (x[i], y[i]) -> (x[i], y[i]) <-- lines with 0 length (== invisible)

If you want to fill the area between two curves, try fill_between. If I remember correct, you should be able to use it as

plt.fill_between([x, y], [x, yhalf])

Upvotes: 2

Related Questions