Skip to main content

Matplotlib styles for HEP

Project description

DOI Scikit-HEP

Build Status GitHub Actions Status: CI GitHub Actions Status: Publish

PyPI version Supported Python versions

Hits PyPI download week

Binder

A set of helpers for matplotlib to more easily produce plots typically needed in HEP as well as style them in way that's compatible with current collaboration requirements (ROOT-like plots for CMS, ATLAS, LHCb, ALICE).

Installation

pip install mplhep

Getting Started

Styling

import matplotlib.pyplot as plt
import mplhep as hep
plt.style.use(hep.style.ROOT) # For now ROOT defaults to CMS
# Or choose one of the experiment styles
plt.style.use(hep.style.CMS)
# or
plt.style.use(hep.style.ATLAS)
# or
plt.style.use(hep.style.LHCb)
# or
plt.style.use(hep.style.ALICE)

Experiment specific style are also available. If the default styles are not what you need, I'd be happy to merge in new styles or modify the current ones.

Default experiment labels are also available

# Overall - both left and right annotation
hep.<experiment>.label()
# Just experiment label and <text> such as 'Preliminary' or 'Simulation'
hep.<experiment>.text(<text>)

Plotting

1D Histograms

h, bins = [2, 3, 2], [0, 1, 2, 3]
hep.histplot(h, bins)

2D Histograms

import numpy as np
xbins, ybins = [0, 1, 2, 3], [0, 1, 2, 3]
H = np.array([[2,3,2], [1,2,1], [3,1,3]])
hep.hist2dplot(H, xbins, ybins)

Several useful style adjustments differing form mpl defaults are also available separately or within

hep.mpl_magic()
  • align axis labels to the right
  • Set lower ylim to 0, if no data is obscured
  • Autoscale upper ylim to fit legend without overlapping with plots

Basic Use

Styling

Minimal Example

import numpy as np
import matplotlib.pyplot as plt
+ import mplhep as hep

x = np.random.uniform(0, 10, 240)
y = np.random.normal(512, 112, 240)
z = np.random.normal(0.5, 0.1, 240)

+ plt.style.use(hep.style.ROOT)
f, ax = plt.subplots()
ax.scatter(x,y, c=z);

*(gray padded to see figure size)

Plotting

A pre-binned histogram plotter is provided, as this functionality is currently awkward in mpl.

import numpy as np
import matplotlib.pyplot as plt
+ import mplhep as hep

h, bins = np.histogram(np.random.normal(10,3,1000))

f, ax = plt.subplots()
- ax.step(bins, np.r_[h, h[-1]], step='post')
+ hep.histplot(h, bins)

Additional functionality is also wrapped inside.

  • if h is a list of arrays or a 2d array, separate histograms will be plotted
  • stack=True stack plots
  • yerr={None | True | array of ndim = h.ndim | array of ndim = h.ndim + 1} is available to plot { no | Poisson | one-sided | two-sided } errors.
  • density=True show density
  • weights
  • histype={'step' | 'fill'}
  • edges when plotting with 'step' close the shape outside

An effort has been made to provide API as close as possible to plt.hist()

2D Histogram plotter is also included

import numpy as np
import matplotlib.pyplot as plt
import mplhep as hep

fig, ax = plt.subplots()

xedges = [0, 1, 3, 5]
yedges = [0, 2, 3, 4, 6,7]
x = np.random.normal(2, 1, 100)
y = np.random.normal(4, 1, 100)
H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))

hep.hist2dplot(H, xedges, yedges)

More Information

Available styles:

  • plt.style.use(style.ROOT) - Default (figure 10x10 inches, full column size)

  • plt.style.use(style.ROOTlegacy) - Same as ROOT style above, but use ROOT fonts - Helvetica, fallback to Arial - instead of TeX Gyre Heros, requires font to be already available on the system

  • plt.style.use(style.ROOTs) - Default (figure 6x6 inches, half column size)

  • plt.style.use(style.fira) - use Fira Sans

  • plt.style.use(style.firamath) - use Fira Math

  • plt.style.use(style.ATLAS) - use default ATLAS style from https://github.com/kratsg/ATLASstylempl, note it defaults to Helvetica, which is not supplied in this package as explained below, and will only work properly if already available on the system

Styles can be chained:

  • e.g. plt.style.use([style.ROOT, style.fira, style.firamath])
  • reappearing rcParams get overwritten silently

Styles can be modified on the fly

  • Since styles are dictionaries and they can be chained/overwritten they can be easiely modified on the fly. e.g.
plt.style.use(style.ROOT)
plt.style.use({"font.sans-serif":'Comic Sans MS'})

Styling with LaTeX

  • plt.style.use(style.ROOTtex) - Use LaTeX to produce all text labels
  • Requires having the full tex-live distro
  • True Helvetica
  • Use sansmath as the math font
  • Takes longer and not always better
  • In general more possibilities, but a bit more difficult to get everything working properly

Experiment annotations

+ plt.style.use(hep.cms.style.ROOT)
+ ax = hep.cms.cmslabel(data=False, paper=False, year='2017', ax=ax)

Plot helper functions

Box (or other) aspect

Square plot with subplot (works with tight_layout())

Append a new axes, without modifying the original

Notes

Consistency & Fonts

As it is ROOT does not come with any fonts and therefore relies on using system fonts. Therfore the font in a figure can be dependent on whether it was produced on OSX or PC. The default sans-serif font used is Helvetica, but it only comes with OSX, in Windows this will silently fallback to Arial.

License

Both Helvetica and Arial are proprietary, which as far as fonts go means you can use it to create any text/graphics once you have the license, but you cannot redistribute the font files as part of other software. That means we cannot just package Helvetica with this to make sure everyone has the same font in plots.

Luckily for fonts it seems only the software is copyrighted, not the actual shapes, which means there are quite a few open alternatives with similar look. The most closely resembling Helvetica being Tex Gyre Heros

Tex Gyre Heros

http://www.gust.org.pl/projects/e-foundry/tex-gyre/heros

You can compare yourself if the differences are meanigful below.

They are Tex Gyre Heros, Helvetica and Arial respecively.

Math Fonts

  • Math fonts are a separate set from regular fonts due to the amount of special characters
  • It's not trivial to make sure you get a matching math font to your regular font
  • Most math-fonts are serif fonts, but this is not ideal if one wants to use sans-serif font for normal text like Helvetica or Arial
  • The number of sans-serif math-fonts is very limited

For consistent styling Fira Sans is included as well.

Default Fira Sans

https://github.com/mozilla/Fira

Math font extension

https://github.com/firamath/firamath

What doesn't work

Context styles and fonts

with pyplot.style.context(style.ROOT):
    plotting...

For now one has to set the style globally

plt.style.use(style.ROOT)

Use in publications

Updating list of citations and use cases of mplhep in publications:

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mplhep-0.1.36.tar.gz (5.4 MB view details)

Uploaded Source

Built Distribution

mplhep-0.1.36-py3-none-any.whl (5.4 MB view details)

Uploaded Python 3

File details

Details for the file mplhep-0.1.36.tar.gz.

File metadata

  • Download URL: mplhep-0.1.36.tar.gz
  • Upload date:
  • Size: 5.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.7.9

File hashes

Hashes for mplhep-0.1.36.tar.gz
Algorithm Hash digest
SHA256 7f3953fbb61d5ccc2d45bb435adb2f21aa4f62c6b61c918244b26b4e51d85871
MD5 9694fdcff3065183f6cb058077c26927
BLAKE2b-256 8de332b0ba3192e362b8e531e0f836a829bff49b504b4fcf1864ae8cc221e44f

See more details on using hashes here.

File details

Details for the file mplhep-0.1.36-py3-none-any.whl.

File metadata

  • Download URL: mplhep-0.1.36-py3-none-any.whl
  • Upload date:
  • Size: 5.4 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/49.6.0 requests-toolbelt/0.9.1 tqdm/4.48.2 CPython/3.7.9

File hashes

Hashes for mplhep-0.1.36-py3-none-any.whl
Algorithm Hash digest
SHA256 a059b8dab2f9f2e502a24c68aa048958e9e0552b6c479805ed6b8f62ae81b428
MD5 f52f2d7b65ffb762852dd8b23996b629
BLAKE2b-256 6d336c5d0e1318fa5ca404ac2ce00cc13e71c99e2f78372242f9b9f44c80721d

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page