How to automatically set the axes with the plot? sns.kdeplot

Viewed 409

I have not been able to configure the plot image with the field drawing. The data provider uses the measures x = 105 and y = 68.

Even in this picture you can see that the goals are out of bounds.

matplotsoccer.field('white',figsize=10, show=False)
    
#Tidy Axes
plt.axis('Off')
   
    sns.kdeplot(df_acciones_ataque["x"],df_acciones_ataque["y"],n_levels=50, shade="True",cmap = 'coolwarm')
    
plt.ylim(0, 68)
plt.xlim(0,105)
    
#plt.suptitle("Acciones de Contraataques y Ataque Elaborado", fontsize=12)
plt.tight_layout(pad=0, w_pad=0, h_pad=0)
#plt.subplots_adjust(top=0.95)
    
    
#Display Pitch
plt.show()

enter image description here

1 Answers

For a 2D kdeplot, Seaborn chooses the limits from the given data points. In the latest version (now 0.11.1), you can set a threshold (thres=) to prevent the lowest layer to be plotted. Setting thres=0 will draw all layers; the best value depends on the data and what you want to show. In older versions, one could use shade_lowest=False.

Apart, there is clim which limits the area (but can not make it larger). To have the image nicely filled to the desired area, one could use both clim and explicitly add a rectangle with the color of the lowest level:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
import seaborn as sns

np.random.seed(1234)
fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, figsize=(18, 5))
for ax in (ax1, ax2, ax3):
    ax.plot([0, 0, 105, 105, 0], [0, 68, 68, 0, 0], color='black')
    ax.plot([105 / 2, 105 / 2], [0, 68], color='black')
    ax.add_patch(plt.Circle((105 / 2, 68 / 2), 9.15, fc='none', ec='black'))
    ax.set_aspect('equal')
    cmap = plt.cm.get_cmap('coolwarm')
    sns.kdeplot(x=np.random.normal(105 / 2, 12, 200), y=np.random.normal(68 / 2, 8, 200), n_levels=50,
                shade="True", cmap=cmap, clip=((0, 105), (0, 68)), thresh=0 if ax == ax1 else 0.002, ax=ax)
    ax.set_xlim(-2, 107)
    ax.set_ylim(-2, 70)
ax1.set_title('drawing the zero level')
ax2.set_title('without drawing the zero level')
ax3.add_patch(Rectangle((0, 0), 105, 68, ec='none', fc=cmap(0), zorder=0))
ax3.set_title('adding a rectangle for the zero level')
plt.show()

example plot

Related