Search code examples
pandasdataframematplotlibplotcolorbar

X-axis label doesn't show on Pandas DataFrame plot with colorbar


I want to make a pandas.DataFrame.plot with colorbar. For reproducibility, here I use the code in this post on stack overflow.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import itertools as it

# [ (0,0), (0,1), ..., (9,9) ]
xy_positions = list( it.product( range(10), range(10) ) )

df = pd.DataFrame( xy_positions, columns=['x','y'] )

# draw 100 floats
df['score'] = np.random.random( 100 )

ax = df.plot( kind='scatter',
              x='x',
              y='y',
              c='score',
              s=500,
              xlabel='x')
ax.set_xlim( [-0.5,9.5] )
ax.set_ylim( [-0.5,9.5] )
plt.tight_layout()

However, in my environment the figure doesn't show x-axis somehow. So I try to add ax.set_xlabel("x label") in the code, but the output doesn't change.

Figure

Here are the package versions of my Python environment.

  • Python 3.8.12
  • pandas 1.4.0
  • matplotlib 3.5.1

Is there any suggestion of this issue? Thanks!

Additional information: I use macOS Big Sur version 11.6 on MacBook Pro M1.


Solution

  • Can you try:

    fig, ax = plt.subplots()
    cm = plt.cm.get_cmap('Greys')
    
    sc = ax.scatter(df['x'], df['y'], s=500, c=df['score'],
                    vmin=df['score'].min(), vmax=df['score'].max(), cmap=cm)
    cb = fig.colorbar(sc)
    t = cb.set_label('score', rotation=-90)
    
    ax.set_xlim( [-0.5,9.5] )
    ax.set_ylim( [-0.5,9.5] )
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    
    plt.tight_layout()
    plt.show()
    

    Output:

    enter image description here