-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
Problem
When x is 1D and y is 2D, the expression plot(x, y) behaves differently in Matplotlib and MATLAB. Matplotlib requires that y.shape[0] == x.size and always plots the columns of y against x. MATLAB will plot by y by columns if its first dimension is compatible with x, but if it is not, and the second dimension of y is compatible with x, then it will plot y by rows.
The following code works in MATLAB, for example:
x = linspace(0, 2*pi); % Size: [1 x 100]
k = (0:2)'; % Size: [3 x 1]
y = sin(k*x); % Size: [3 x 100]
plot(x, y) % Second dimensions are the same
plot(x, y') % Second dimension of x is the same as first dimension of y'In the similar code below, Matplotlib returns an error for plot(x, y), but not for plot(x, y.T):
x = np.linspace(0, 2 * np.pi) # Shape: (50,)
k = np.arange(3). # Shape: (3,)
y = np.sin(np.outer(k, x)) # Shape: (3, 50)
plt.plot(x, y) # Returns ValueError
plt.plot(x, y.T) # y.T has shape (50, 3), compatible with xThe NumPy broadcasting rules and FFT routines are organized around row operations, which forces a choice between rows and columns—see here for an example.
Proposed solution
When x is 1D and y is 2D, plot y by columns when y.shape[0] == x.size, but also try to plot y by rows when y.shape[0] != x.size.