python-3.xdataframematplotlibtopologycontourf

contour plot or topological map with unequal sized arrays?


I have a dataframe with 20 rows and 100 columns (dummy data): enter image description here

Right now I'm plotting the data as a heat map, but I'll like to have a more topological view of the data.

I want to create something like a contour map:

enter image description here

But with visible points, kind of like this map:

enter image description here

(from the contour plot of irregularly spaced data documentation)

Is there a way to do this using contour or isobar or something else? From what I can tell for the contour plot documentation, the arrays for X, Y, and Z need to be of equal size, but my dataframe has to have 20 rows and 100 columns.

Thanks in advance!!


Solution

  • If your data is in a dataframe, then it is regularly spaced. I assume x and y coodinates shall be the dataframe's column and index indices, respectively. Then you can simply make a contour plot from the dataframe and then overplot the grid points on the same Axes.

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    
    # create sample dataframe
    x = np.linspace(-2, 2, 100)
    y = np.linspace(-2, 2, 20)
    xx, yy = np.meshgrid(x, y)
    z = np.exp(-(xx**2 + yy**2))
    df = pd.DataFrame(z)
    
    # plot it
    fig, ax = plt.subplots(figsize=(20, 10))
    cont = ax.contourf(df)
    ax.plot(df.columns, np.broadcast_to(df.index, (len(df.columns),len(df)) ), 'k.')
    fig.colorbar(cont)
    

    enter image description here