pythonmatplotlibcontour

plt.contour() plots series of lines instead of a contour line


I aim to plot a contour plot of flux, but instead of closed contour curves, plt.contour() returns a series of lines with the same height.

Psi is defined as a np.array and has a 320 by 200 shape.

fig, ax = plt.subplots()
r_end = grid_start[0] + grid_step[0] * grid_size[0]
z_end = grid_start[1] + grid_step[1] * grid_size[1]

X = np.arange(grid_start[0], r_end, grid_step[0]) # shape (200,)
Y = np.arange(grid_start[1], z_end, grid_step[1]) # shape (320,)

x, y = np.meshgrid(X, Y)
CS = ax.contour(x, y, Psi)
ax.clabel(CS, fontsize=10)

The result looks very weird:

all contours image

I also created contour plots with some levelling for enhanced visibility.

contour plot, level 0

contour plot, level 25

The desired result is smth like this: desired Psi Contours

If I reshape the given array to (3200,20) the periodicity is lost, but it is still weird.

reshaped result

How can I fix this issue? Thanks for your help.


Solution

  • I think that your original data is a different size: maybe 3200 by 20, not 320 by 200. (You should check). The datafile does have 320 rows of 200 columns, but I suspect that is an artefact: maybe they were simply limited by line length.

    If I reshaped to 3200 by 20 then this is what I get:

    enter image description here

    
    import numpy as np
    import matplotlib.pyplot as plt
    
    NX, NY = 320, 200
    psi = np.zeros( ( NX, NY ) )
    
    with open( 'flux_test.txt' , 'r' ) as input:
        for row, line in enumerate( input ):
            for col, str in enumerate( line.split() ):
                psi[row,col] = float( str )
    
    psi = psi.reshape( 3200, 20 )
    
    
    fig, ax = plt.subplots(figsize=[10, 6])
    CS = ax.contour( psi )
    plt.show()
    

    Interestingly, if I reshape to 200 by 320 then I get the following which, I suppose, might also be right. I don't know what you are trying to get as an end result. Note that both Fortran and Matlab use column-major array storage order - the opposite of Python's numpy - so I still think you need to go back to how the data file was created. You aren't giving us that information.

    enter image description here