andrewrowlinson / mplsoccer Goto Github PK
View Code? Open in Web Editor NEWFootball pitch plotting library for matplotlib
License: MIT License
Football pitch plotting library for matplotlib
License: MIT License
Add a 3D pitch class.
I was using the Sbopen parser to fetch data from the Statsbomb database and encountered the following error:
My internet connection has been working smoothly, and previous calls to the Statsbomb dataset have been successful, but after this issue arose for the first time, I have been unable to fetch any data at all.
Hi Andrew,
Would it be possible to return an extra fields (arrays) with the positions and cards related to players in flatten_lineup function?
Thanks.
Regards,
Paco.
Add speedometer plots for showing average speeds of players from https://github.com/znstrider/speedo by @znstrider.
Hi Andrew,
I have the following error with your 1.0.7 version while getting a match (competitionId: 16, seasonId: 76):
from mplsoccer import Sbopen
parser = Sbopen(dataframe=True)
matches = parser.match(16, 76)
KeyError: 'match_date'
The stack trace shows that the line 409 is involved in the exception:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mplsoccer/statsbomb.py", line 409, in _match_dataframe
Do you know what is wrong?
Thanks again :)
Cheers,
Paco.
Add a Delaunay triangulation method to the Pitch classes.
Inspiration:
Use scipy's Delaunay (https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html) and follow a similar style to the voronoi
method.
Some people have made the pitch markings dashed. Occasionally just the perimeter of the pitch. It would be fairly easy to add an argument to allow the linestyle to be changed to make this easier.
When I try to use the ax parameter in make_pizza() (e.g ax=axs[2]), I always get the following message:
"AttributeError: 'Axes' object has no attribute 'set_rorigin'"
This means I can only plot a pizza plot on another figure, not on a figure with multiple axes. I can add code examples if needed, but since I've tested this multiple times, I figured it isn't required.
Hi Andrew,
Using StatsBomb and your framework, I am trying to add the following information inside the animation function:
pitch.annotate('?', (awayTeamXandYPosition.x[i], awayTeamXandYPosition.y[i]),
va='center', ha='center', color='white',
fontsize=15, ax=ax['pitch'])
Could you help me?
Thank you!
Cheers,
Paco.
A direction play/attack arrow is often displayed on pitches.
Add an example to the gallery of ways of doing this. The examples are found here:
The examples are structured as python scripts using Sphinx Gallery. See the following guide about how to structure these scripts files:
https://sphinx-gallery.github.io/stable/syntax.html
Hi,
when I create a simple radar cart:
from mplsoccer.radar_chart import Radar
## parameter names
params = ['xAssist', 'Key Passes', 'Crosses Into Box', 'Cross Completion %', 'Deep Completions',
'Progressive Passes', 'Prog. Pass Accuracy', 'Dribbles', 'Progressive Runs',
'PADJ Interceptions', 'Succ. Def. Actions', 'Def Duel Win %']
## range values
ranges = [(0.0, 0.15), (0.0, 0.67), (0.06, 6.3), (19.51, 50.0), (0.35, 1.61),
(6.45, 11.94), (62.9, 79.4), (0.43, 4.08), (0.6, 2.33),
(4.74, 7.2), (8.59, 12.48), (50.66, 66.67)]
min_range = [0.0,0.0,0.06,19.51,0.35,6.45,62.9,0.43,0.6,4.74,8.59,50.66]
max_range = [0.15, 0.67, 6.3, 50.0,1.61,11.94,79.4,4.08,2.33,7.2,12.48,66.67]
## parameter value
values = [0.11, 0.53, 0.70, 27.66, 1.05, 6.84, 84.62, 4.56, 2.22, 5.93, 8.88, 64.29]
## instantiate object
radar = Radar(params, min_range, max_range)
fig, ax = radar.setup_axis() # format axis as a radar
rings_inner = radar.draw_circles(ax=ax, facecolor='#ffffff', edgecolor='#000000') # draw circles
radar_output = radar.draw_radar(values, ax=ax,
kwargs_radar={'facecolor': '#709775','alpha': 0.8},
kwargs_rings={'facecolor': '#709775', 'alpha':0.8}) # draw the radar
range_labels = radar.draw_range_labels(ax=ax, fontsize=8)
param_labels = radar.draw_param_labels(ax=ax, fontsize=12, **{'color':'#ffffff'}) # draw the param labels
I get the following visualization where (depending on the ring) the color of the polygon is lighter or darker green:
Is there a way to avoid the changing colors of the polygon for every ring?
Replace setup with pyproject.toml and setup.cfg. Add version to init. Use flit or hatch:
https://flit.pypa.io/en/latest/index.html#
https://hatch.pypa.io/latest/
The docs are not building for py_pizza examples when some of the linewidth arguments are zero. For example:
mplsoccer/mplsoccer/py_pizza.py
Lines 316 to 319 in bce816c
The docs error is:
ValueError: At least one value in the dash list must be positive
This seems to be related to:
matplotlib/matplotlib#8821
Add an example of visualizing a stream of event data.
Inspiration:
The examples are structured as python scripts using Sphinx Gallery. See the following guide about how to structure these scripts files:
https://sphinx-gallery.github.io/stable/syntax.html
Adding pitch_alpha would allow more effects like glowing pitch lines (see https://github.com/dhaitz/mplcyberpunk). This would require changing the six yard box and penalty area to lines instead of rectangles. This is because the boxes currently overlap with the pitch sidelines and the boxes overlap and with transparency the overlap would be a darker colour.
Hello
I'm trying to run this basic example in the docs:
from mplsoccer.pitch import Pitch
pitch = Pitch(pitch_color='grass', line_color='white', stripe=True)
fig, ax = pitch.draw()
But when I run the above nothing shows up, I tried creating a plot with matplotlib and that showed up with no issues.
I am on MacOS 10.15.6 running python 3.8.6.
Any help would be appreciated.
Add drawing of zone lines using zone
(boolean) keyword in Pitch classes.
Add a heatmap method for the zones.
Inspiration:
The positions are already calculated via _juego_de_posicion. This could be done using a similar style to the _draw_juego_de_posicion/ bin_statistic_positional methods (only needs one set of xedges/ yedges).
There is a problem when mplsoccer is combined with Streamlit. The amount of memory keeps increasing when creating new charts. It seems to be caused by the custom handlers.
mplsoccer/mplsoccer/linecollection.py
Line 178 in d9956e8
Line 113 in d9956e8
Is there a better way of doing this?
Greetings! This is not an issue but maybe just a comment or quick question. On the heatmap examples, one uses brighter colors for high values...
...whereas the next features brighter colors for lower values.
Is there a contradicton, or maybe I'm missing something here? Normally I would asume that, in a heatmap, "darker" always means "higher". Thanks in advance and congratulations for mplsoccer, a very useful tool.
Hi,
I am plotting three pitches side by side using pitch.grid()
and creating a heatmap on each one with something like pitch.heatmap(bin_stat_i, axs[i], cmap='Reds', edgecolors='#f9f9f9')
, and the pitch.label_heatmap() function as well.
The numeric labels are comparable across pitches, but the colors are not, they each use their own scale based on the min and max of the individual heatmap. Is there a way for the three to use the same colour scale?
Thank you for any help!
Matplotlib 3.6 changed the argument transOffset to offset_transform:
matplotlib/matplotlib#21965
With the current code the following error occurs when creating the docs:
TypeError: HandlerFootball.create_collection() got an unexpected keyword argument 'offset_transform'.
This code needs to be changed for compatibility with Matplotlib 3.6:
mplsoccer/mplsoccer/scatterutils.py
Lines 277 to 282 in 99976cb
Hi,
Some of my old code is not working anymore.
From the changelog I found that this has now changed.
I looked over the documentation, however I do just want to load in some local statsbomb files.
Is this still possible, or can I only work with the online API from now?
Hi Andrew,
I am trying to create a video with your sample code (plot_animation.py):
anim.save('example.mp4', dpi=150, fps=25,
extra_args=['-vcodec', 'libx264'],
savefig_kwargs={'pad_inches':0, 'facecolor':'#457E29'})
As you advanced in your comments, I had problems to download ffmpeg (in this case, using brew), so I found this web site to download the static executable:
After that, my code can generate the video with the previous code, but there are too many overlapping between every animation (the image 1 contains the figures of the image 0, the image 2 contains the figures of the image 1, etcetera)
Do you know how to solve that?
Thank you.
It might be possible to combine py_pizza into radar to make it more modular, but maintain py_pizza for backward compatibility.
Hi Andrew:
Just checking this easy to fix problem,
read_event(f'match_id.json', warn=False)
` 157 # split location info to x, y and (z for shot) columns and drop old columns
--> 158 _split_location_cols(df, 'location', ['x', 'y'])
ValueError: 2 columns passed, passed data had 3 columns
`
Collecting scipy
Using cached scipy-1.10.0.tar.gz (42.4 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Installing backend dependencies ... done
Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error
× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [67 lines of output]
The Meson build system
Version: 1.0.0
Source dir: /private/var/folders/hk/4ryb7f7d4ln3rh6dlm3khpcr0000gn/T/pip-install-fjm6g3k5/scipy_091083c83de84fe18f7cfcff51fcbf29
Build dir: /private/var/folders/hk/4ryb7f7d4ln3rh6dlm3khpcr0000gn/T/pip-install-fjm6g3k5/scipy_091083c83de84fe18f7cfcff51fcbf29/.mesonpy-ju3scbhx/build
Build type: native build
Project name: SciPy
Project version: 1.10.0
C compiler for the host machine: cc (clang 10.0.1 "Apple LLVM version 10.0.1 (clang-1001.0.46.4)")
C linker for the host machine: cc ld64 450.3
C++ compiler for the host machine: c++ (clang 10.0.1 "Apple LLVM version 10.0.1 (clang-1001.0.46.4)")
C++ linker for the host machine: c++ ld64 450.3
Host machine cpu family: x86_64
Host machine cpu: x86_64
Compiler for C supports arguments -Wno-unused-but-set-variable: NO
Compiler for C supports arguments -Wno-unused-function: YES
Compiler for C supports arguments -Wno-conversion: YES
Compiler for C supports arguments -Wno-misleading-indentation: NO
Compiler for C supports arguments -Wno-incompatible-pointer-types: YES
Library m found: YES
Fortran compiler for the host machine: gfortran (gcc 12.2.0 "GNU Fortran (Homebrew GCC 12.2.0) 12.2.0")
Fortran linker for the host machine: gfortran ld64 530
Compiler for Fortran supports arguments -Wno-conversion: YES
Checking if "-Wl,--version-script" : links: NO
Program cython found: YES (/private/var/folders/hk/4ryb7f7d4ln3rh6dlm3khpcr0000gn/T/pip-build-env-cj4t6m7a/overlay/bin/cython)
Program python found: YES (/Users/nathaniel/Desktop/futbolSci2/soccerSci2/bin/python3)
Did not find pkg-config by name 'pkg-config'
Found Pkg-config: NO
Program pythran found: YES (/private/var/folders/hk/4ryb7f7d4ln3rh6dlm3khpcr0000gn/T/pip-build-env-cj4t6m7a/overlay/bin/pythran)
Run-time dependency threads found: YES
Library npymath found: YES
Library npyrandom found: YES
Found CMake: /usr/local/bin/cmake (3.25.2)
Run-time dependency openblas found: NO (tried pkgconfig, framework and cmake)
Run-time dependency openblas found: NO (tried framework and cmake)
../../scipy/meson.build:134:0: ERROR: Dependency lookup for OpenBLAS with method 'pkgconfig' failed: Pkg-config binary for machine 1 not found. Giving up.
The edit on GitHub link on the page for Pitch Basics returns a 404 - Page not found error. The Link is on the top right of the page.
Where can I find detailed documentation on facecolor argument of Radar.draw_circle method ?
Hi,
There is a bug in Statsbomb.py (function "read_lineup") in the following line:
match_id = os.path.basename(path_or_buf[:-5])
It should be:
match_id = os.path.basename(path_or_buf)[:-5]
The current exception is "TypeError: 'PosixPath' object is not subscriptable"
My Python version is 3.7.3
Thank you!
Add a scatter density method to the Pitch classes.
Inspiration:
In principle, this could be added by using the c
and cmap
arguments of Axes.scatter. Calculating the density via kernel density estimation and using this as the c
argument.
Hello,
I've seen an issue where somebody else has also asked this, and the answer was that it is left to right. Is this also the case for StatsBomb event data?
Sorry for not knowing and disturbing you, it's only that I'm scared of creating a heatmap that is distorted due to attacking direction.
Add an example for displaying a cmap using markers, as sometimes it's preferred to a color bar.
Inspiration:
Utdarena had an idea for a beginners guide on "Getting Started with mplsoccer":
It would be good to have a video embedded in the docs.
Add a convex hull method to the Pitch classes.
Inspiration:
Use scipy's ConvexHull (https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.ConvexHull.html) and follow a similar style to the voronoi
method.
Hi,
I apologize if this is not the right place. I am new to Python Programming. I am trying to install mplsoccer using pip and getting an error. It must be something I am doing wrong. Appreciate any help I can get for this.
pip install mplsoccer
ERROR: Command errored out with exit status 1:
command: 'c:\python\python394\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\naman\\AppData\\Local\\Temp\\pip-install-z8r0sc11\\mplsoccer_07f310df0dd94fbb840e04b488eebeb9\\setup.py'"'"'; __file__='"'"'C:\\Users\\naman\\AppData\\Local\\Temp\\pip-install-z8r0sc11\\mplsoccer_07f310df0dd94fbb840e04b488eebeb9\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\naman\AppData\Local\Temp\pip-pip-egg-info-guzrhz9z'
cwd: C:\Users\naman\AppData\Local\Temp\pip-install-z8r0sc11\mplsoccer_07f310df0dd94fbb840e04b488eebeb9\
Complete output (11 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\naman\AppData\Local\Temp\pip-install-z8r0sc11\mplsoccer_07f310df0dd94fbb840e04b488eebeb9\setup.py", line 3, in <module>
import mplsoccer
File "C:\Users\naman\AppData\Local\Temp\pip-install-z8r0sc11\mplsoccer_07f310df0dd94fbb840e04b488eebeb9\mplsoccer\__init__.py", line 5, in <module>
from mplsoccer.pitch import *
File "C:\Users\naman\AppData\Local\Temp\pip-install-z8r0sc11\mplsoccer_07f310df0dd94fbb840e04b488eebeb9\mplsoccer\pitch.py", line 7, in <module>
from mplsoccer._pitch_plot import BasePitchPlot
File "C:\Users\naman\AppData\Local\Temp\pip-install-z8r0sc11\mplsoccer_07f310df0dd94fbb840e04b488eebeb9\mplsoccer\_pitch_plot.py", line 8, in <module>
import seaborn as sns
ModuleNotFoundError: No module named 'seaborn'
Add a method for plotting an arc for the average distance of shots etc.
Inspiration:
https://twitter.com/petermckeever/status/1321137690964828165
It would need to account for the unequal aspect ratio of some of the pitches (e.g. opta
, wyscout
and metricasports
). See the _init_circles_and_arcs_equal_aspect method. What units should this be in (meters)?
Implement curved text for radars and pizza plots. @petermckeeverPerform recommended that the text labels for the parameter names (e.g. expected goals) around the edges of the radar/pizza plot look curved.
The following stackoverflow post is related to this: https://stackoverflow.com/questions/19353576/curved-text-rendering-in-matplotlib/44521963#44521963
Add a method for plotting pitch control. Devin Pleuler has a method in northpitch called overlay_surface: https://github.com/devinpleuler/northpitch.
How to generate an example? Is there an open source version of pitch control that can be installed via pip?
It would be great to add mplsoccer to the conda-forge channel.
The game 3 data in the Metrica Open Data repository (https://github.com/metrica-sports/sample-data) have information about player numbers. How to plot an animation with the player numbers?
Add pass sonar method to Pitch classes.
Inspiration:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.