'Division of two plt.hist2d
I have two 2D-histograms, one containing a total number of shots and the other containing the total number of shots succeeded. I would like to divide these two histograms in order to have one with the success rate of shots per zone.
This is the initial data frame :

This is my first 2D-histogram with the total number of shots :
This is my second 2D-histogram with the total number of shots succeeded :
This is my code for both histograms :
fig = plt.figure() #set up the figures
fig.set_size_inches(10, 7)
ax = fig.add_subplot(1,1,1)
draw_pitch_horizontal(ax) #overlay our different objects on the pitch
colors = {'Goal Kicked':'tab:blue','Goal Missed':'tab:red'}
penalty = plt.hist2d(kick.nouveau_x,kick.nouveau_y, bins=[np.arange(0,130,10),np.arange(0,90,10)],cmap=plt.cm.Reds)
plt.ylim(-2, 82)
plt.xlim(-2, 122)
plt.colorbar()
plt.title('Map des pénalités',fontsize=16)
plt.axis('off')
plt.show()
fig.set_size_inches(10,7)
ax = fig.add_subplot(1,1,1)
draw_pitch_horizontal(ax) #overlay our different objects on the pitch
colors = {'Goal Kicked':'tab:blue','Goal Missed':'tab:red'}
kicked = plt.hist2d(kick[kick.outcome == 'Goal Kicked'].nouveau_x,kick[kick.outcome == 'Goal Kicked'].nouveau_y, bins=[np.arange(0,130,10),np.arange(0,90,10)],cmap=plt.cm.Reds)
plt.ylim(-2, 82)
plt.xlim(-2, 122)
plt.colorbar()
plt.title('Map des pénalités réussies',fontsize=16)
plt.axis('off')
plt.show()
I tried to divide my variables penalty and kicked but then I have a list of arrays and I don't know how to plot it on my pitch.
Solution 1:[1]
The hist2d function returns 4 things: the 2-D array of data (you want this), the bin edges in each direction (which you already have), and the quadmesh object (which you don't really need). You can use the 2-D arrays to compute what you want.
Replace the penalty = ... line in the first blocks with:
bins=[np.arange(0,130,10), np.arange(0,90,10)]
success = kick.outcome == 'Goal Kicked'
h_penalty, xedges, yedges, image = plt.hist2d(kick.nouveau_x,
kick.nouveau_y,
bins=bins,
cmap=plt.cm.Reds,
)
And replace the kicked = ... line in the second block with:
h_kicked, xedges, yedges, image = plt.hist2d(kick[success].nouveau_x,
kick[success].nouveau_y,
bins=bins,
cmap=plt.cm.Reds,
)
Then you can do:
success_rate = 100 * h_kicked / h_penalty
And you can show that with something like im = plt.imshow(success_rate), or another quadmesh.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kwinkunks |


