user3185775
user3185775

Reputation: 207

Error when using plt.contour: Input z must be a 2D array

I get the error message "Input z must be a 2D array" whe using matplotlib's plt.contour function.

I've already tried with meshgrid but it does not work, I can't really find the issue. E = np.zeros(2500) is an array so I cant find what's wrong.

import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mkgrid2d import *

W1 = np.linspace(-1.0,3.0,num = 50)
W0 = np.linspace(-2.0,4.0,num = 50)

w11 = 1.00
w00=1.0

w = np.array([[w11],[w00]],dtype=float)

mew = 0
sigma = np.sqrt(2)


Npts=50;rd.seed(1)
x1=rd.rand(1,Npts)*10.-5.0 #Npts uniformemente distribuídos
r = np.random.normal(mew, sigma, 50)*2.-1.0#ruído gaussiano distribuído

X = np.vstack((x1,np.ones((1,x1.shape[1]))))
X = X.astype('float') #converter para float

N=Npts 

y = np.dot(w.T,X) + r
E= np.zeros(2500) 

"E" will be the Z for Contour

count = 0
for i in range (len(W1)):
    for j in range (len (W0)):
        w1 = np.array([W1[i],W0[j]])
        yn = np.dot(w1.T,X)
        E[count] = (1./50)*(np.sum((y-yn)**2))
        count +=1

plt.figure()
CS = plt.contour(W1,W0,E)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('Simplest default with labels')
        

Upvotes: 4

Views: 4893

Answers (1)

tmdavison
tmdavison

Reputation: 69116

As the error message says, you need your E array to be 2D, of shape (50,50), not a 1D array of shape (2500).

There's a couple of ways around this:

  1. reshape your E after assigning it

    E = E.reshape(len(W1),len(W0))
    
  2. create E with the correct shape in the first place, then use your i and j to index it

    E = np.zeros((len(W1),len(W0)))
    
    for i in range (len(W1)):
        for j in range (len (W0)):
            w1 = np.array([W1[i],W0[j]])
            yn = np.dot(w1.T,X)
            E[i][j] = (1./50)*(np.sum((y-yn)**2))
    

Upvotes: 3

Related Questions