Search code examples
python-3.xpandasmatplotlibmulti-indexcontour

Creating contour plot from Pandas multi-index dataframe


How do I create a contour plot from the following Pandas dataframe named think_or_feel:

              think     feel
cNEU    cOPN        
y         n     27      20
n         n     40      23
y         y     43      25
n         y     97      63

I have tried the following:

X=think_or_feel.columns
Y=think_or_feel.index 
Z=think_or_feel.values
x,y=np.meshgrid(X, Y)
plt.contourf(x,y,Z)

I get the following error: unhashable type: 'numpy.ndarray'

I'd really appreciate any help on this.


Solution

  • I guess the reason is that your index/columns are not numbers, while plt.contourf expects numbers. Let's try:

    X=np.arange(think_or_feel.shape[1])
    Y=np.arange(think_or_feel.shape[0])
    Z=think_or_feel.values
    
    plt.contourf(x,y,Z)
    plt.xticks(X, think_or_feel.columns)
    plt.yticks(Y, think_or_feel.index)
    

    Output:

    enter image description here