Search code examples
pythonmatplotlibseabornheatmapdensity-plot

How to remove the white shade/color from the heatmap using sns.kdeplot()? I just want the red color


from mplsoccer.pitch import Pitch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import kde
from scipy.ndimage import gaussian_filter
from copy import copy
np.random.seed(19680801)

plt.style.use('dark_background')

fields = ['id', 'minute', 'result', 'X1', 'Y','xG','h_a','situation','season',
          'shotType','X']
df=pd.read_csv('shots.csv', skipinitialspace=True, usecols=fields)
fig, ax = pitch.draw()
sns.kdeplot(df.Y, df.X,shade=True, ax=ax, cmap='Reds',
              shade_lowest=False,levels=20,kernel='gau',gridsize=50,
              bw='scott',cut=0,cbar=True,)
ax.set_xlim(ax.get_xlim()[::-1])        # invert the axis
ax.yaxis.tick_right()  
plt.axis('off')
plt.show()

The values df.X & df.Y lie between (0,1). I want the red part only. In matplotlib I used vmin argument eliminate the white part. What can be done here?

Edit: On second thoughts, the White region would be eliminated if the colormap starts from 12 in the fig attached. So the colormap starts from red and ends on dark red. That's what I would like.

Output Heatmap


Solution

  • I would use this approach to pick colours out of your colormap:

    from matplotlib import cm
    from matplotlib.colors import ListedColormap
    
    # select 42 colours from the "Reds" cmap
    red_selection = cm.get_cmap("Reds", 42)
    
    # select half of the colours, closest to Red and assign to a new colormap
    red_cmap = ListedColormap(red_selection(range(42))[21:, :])
    
    from mplsoccer.pitch import Pitch
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    from scipy.stats import kde
    from scipy.ndimage import gaussian_filter
    from copy import copy
    np.random.seed(19680801)
    
    plt.style.use('dark_background')
    
    fields = ['id', 'minute', 'result', 'X1', 'Y','xG','h_a','situation','season',
              'shotType','X']
    df=pd.read_csv('shots.csv', skipinitialspace=True, usecols=fields)
    fig, ax = pitch.draw()
    sns.kdeplot(df.Y, df.X,shade=True, ax=ax, cmap=red_cmap,
                  shade_lowest=False,levels=20,kernel='gau',gridsize=50,
                  bw='scott',cut=0,cbar=True,)
    ax.set_xlim(ax.get_xlim()[::-1])        # invert the axis
    ax.yaxis.tick_right()  
    plt.axis('off')
    plt.show()