Skip to content

[ENH]: Expand shape compatibility of x and y in plot #25915

@jsdodge

Description

@jsdodge

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 x

The 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions