Search code examples
pythonpandasmatplotlibnumpy-ndarraycontour

Contour plot of a dataframe : Error occurs at Z dimension


While making a filled contour plot from a pandas dataframe, the following error occurs every time. I have cross checked the dimension of Z which is 2-D, still the error occurs.

TypeError: Input z must be 2D, not 3D
data = {'10.2': [72,57,56,67,69,136], '10.6':[31,23,19,17,41,74],
        '10.9': [27,96,97,99,18,40], '11.3':[10,98,100,35,67,258], '11.8':[124,92,49,24,88,209]}

df = pd.DataFrame(data)

#### Create a meshgrid from the DataFrame index and columns

x = df.index
y = df.columns
X, Y = np.meshgrid(x,y)

Z = df.values
c = plt.contourf([X, Y], Z)

TypeError: Input z must be 2D, not 3D

#### Cross check the dimension of Z 

Z.ndim # it shows 2

I don't know where I am getting wrong or how to resolve the issue.


Solution

  • The call signature is either contourf(Z) or contourf(X, Y, Z). The [X,Y,] notation of the documentation is confusing, but means that you can pass those if you want. But because you actually put it in brackets, you created a 3D array which matplotlib was interpreting as the Z argument. But you have two other issues.

    1. Y needs to be converted to a numeric type, which you can do by changing the y definition to y = df.columns.astype(float).
    2. Z is the transpose of what it should be, but that can be fixed by doing Z = df.values.T.
    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    
    data = {'10.2': [72,57,56,67,69,136], 
            '10.6':[31,23,19,17,41,74],
            '10.9': [27,96,97,99,18,40], 
            '11.3':[10,98,100,35,67,258], 
            '11.8':[124,92,49,24,88,209]}
    
    df = pd.DataFrame(data)
    
    x = df.index
    y = df.columns.astype(float)
    X, Y = np.meshgrid(x,y)
    
    Z = df.values.T
    c = plt.contourf(X, Y, Z)