Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 21 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,32 +40,31 @@ Documentation can be found at [mplhep.readthedocs.io](https://mplhep.readthedocs
### Styling

```python
import mplhep as hep
hep.style.use(hep.style.ROOT) # For now ROOT defaults to CMS
# Or choose one of the experiment styles
hep.style.use(hep.style.ATLAS)
# or
hep.style.use("CMS") # string aliases work too
# {"ALICE" | "ATLAS" | "CMS" | "LHCb1" | "LHCb2" | "DUNE" | "DUNE1"}
import mplhep as mh
mh.style.use(mh.style.ROOT) # For now ROOT defaults to CMS
# OR
mh.style.use(mh.style.ATLAS)
# OR
mh.style.use("CMS") # string aliases work too
```

Or use `matplotlib` API directly

```python
plt.style.use(hep.style.ROOT)
plt.style.use(mh.style.ROOT)
```
**If the default styles are not what you need, please open an issue.**

Default experiment labels are also available.

```python
# Overall - both left and right annotation
hep.<experiment>.label(<text>, data=<True|False>, lumi=50, year=2017)
# Just experiment label and <text> such as 'Preliminary' or 'Simulation'
hep.<experiment>.text(<text>)
mh.<experiment>.label(<text>, data=<True|False>, lumi=50, year=2017)
# OR
mh.<experiment>.text(<text>)
```

You can use `loc={0..5}` to control the label positioning.
You can use `loc={0..4}` to control the label positioning.

<p float="left">
<img src="tests/baseline/test_label_loc.png" width="100%" />
Expand All @@ -77,7 +76,7 @@ You can use `loc={0..5}` to control the label positioning.

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

#### 2D Histograms
Expand All @@ -86,40 +85,40 @@ hep.histplot(h, bins)
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)
mh.hist2dplot(H, xbins, ybins)
```

# More Information

### Save all labels at once
- `hep.savelabels('test.png')` will produces 4 variation on experiment label
- `mh.savelabels('test.png')` will produces 4 variation on experiment label
- "" -> "test.png"
- "Preliminary" -> "test_pas.png"
- "Supplementary" -> "test_supp.png"
- "Work in Progress" -> "test_wip.png"
- Options can also be specified manually
- `hep.savelabels('test', labels=["FOO", "BAR"], suffixes=["foo.pdf", "bar"])` will produce
- `mh.savelabels('test', labels=["FOO", "BAR"], suffixes=["foo.pdf", "bar"])` will produce
- "FOO" -> "foo.pdf"
- "BAR" -> "test_bar.png"
- Other components of `<experiment>.label()` will remain unchanged.

### Other styles:
- `hep.style.use("fira")` - use Fira Sans
- `hep.style.use("firamath")` - use Fira Math
- `mh.style.use("fira")` - use Fira Sans
- `mh.style.use("firamath")` - use Fira Math

#### Styles can be chained:
- e.g. `hep.style.use(["CMS", "fira", "firamath"])`
- e.g. `mh.style.use(["CMS", "fira", "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 easily modified on the fly. e.g.
```
hep.style.use("CMS")
hep.style.use({"font.sans-serif":'Comic Sans MS'})
mh.style.use("CMS")
mh.style.use({"font.sans-serif":'Comic Sans MS'})
```

#### Styling with LaTeX
- `hep.style.use("CMSTex")` - Use LaTeX to produce all text labels
- `mh.style.use("CMSTex")` - Use LaTeX to produce all text labels
- Requires having the full tex-live distro
- True Helvetica
- Use sansmath as the math font
Expand Down
28 changes: 24 additions & 4 deletions docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,30 +11,50 @@ Primary functions.

.. autofunction:: mplhep.hist2dplot

.. autofunction:: mplhep.funcplot

.. # List all modules when appropriately privatized
.. automodule:: mplhep.plot
:members:


Text functions
========================

Functions to annotate figures in a convenient way. Typically ``append_text`` can be used to place an additional artist after ``add_text``.

.. autofunction:: mplhep.label.add_text

.. autofunction:: mplhep.label.append_text


Experiment label helpers
========================

Experiment specific helpers.

For the effects of the ``label`` method, see also the gallery examples in :ref:`gallery-labels`.

.. autofunction:: mplhep.cms.lumitext

.. autofunction:: mplhep.cms.label

.. autofunction:: mplhep.cms.text

.. autofunction:: mplhep.cms.label
.. autofunction:: mplhep.atlas.label

.. autofunction:: mplhep.atlas.text

.. autofunction:: mplhep.atlas.label
.. autofunction:: mplhep.lhcb.label

.. autofunction:: mplhep.lhcb.text

.. autofunction:: mplhep.lhcb.label
.. autofunction:: mplhep.alice.label

.. autofunction:: mplhep.alice.text

.. autofunction:: mplhep.dune.label

.. autofunction:: mplhep.dune.text


Axes helpers
Expand Down
39 changes: 34 additions & 5 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,47 @@ def linkcode_resolve(domain, info):
return None
if not info["module"]:
return None
mod = importlib.import_module(info["module"])

# Handle module aliasing for experiment modules
module_name = info["module"]
if module_name.startswith("mplhep.") and module_name.split(".")[-1] in [
"cms",
"atlas",
"lhcb",
"alice",
"dune",
]:
# Map aliased modules to their actual module names
alias_map = {
"mplhep.cms": "mplhep.exp_cms",
"mplhep.atlas": "mplhep.exp_atlas",
"mplhep.lhcb": "mplhep.exp_lhcb",
"mplhep.alice": "mplhep.exp_alice",
"mplhep.dune": "mplhep.exp_dune",
}
module_name = alias_map.get(module_name, module_name)

try:
mod = importlib.import_module(module_name)
except ImportError:
return None

modpath = [p for p in sys.path if mod.__file__.startswith(p)]
if len(modpath) < 1:
msg = "Cannot deduce module path"
raise RuntimeError(msg)
modpath = modpath[0]
obj = reduce(getattr, [mod, *info["fullname"].split(".")])

try:
obj = reduce(getattr, [mod, *info["fullname"].split(".")])
except AttributeError:
return None

try:
path = inspect.getsourcefile(obj)
relpath = path[len(modpath) + 1 :]
_, lineno = inspect.getsourcelines(obj)
except TypeError:
except (TypeError, OSError):
# skip property or other type that inspect doesn't like
return None
return f"http://github.com/scikit-hep/mplhep/blob/{githash}/{relpath}#L{lineno}"
Expand Down Expand Up @@ -172,7 +201,7 @@ def linkcode_resolve(domain, info):
ax.plot(x, np.asarray(y), label=label)

kwargs = {
"label": "Preliminary",
"text": "Preliminary",
"data": True,
"ax": ax,
"year": 2016,
Expand All @@ -188,7 +217,7 @@ def linkcode_resolve(domain, info):
elif "dune" in style.lower():
mplhep.dune.label(**kwargs)
ax.legend()
ax.set_xlabel("$m_{\mu\mu}$ [GeV]")
ax.set_xlabel(r"$m_{\mu\mu}$ [GeV]")
ax.set_ylabel("Events")
path = Path(
here / f"_static/_generated/{style}/{histtype}/pos{position}.png"
Expand Down
6 changes: 3 additions & 3 deletions docs/source/install.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ primary functionality can be accessed as follows:

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

# Load style sheet
plt.style.use(hep.style.CMS) # or ATLAS/LHCb2
plt.style.use(mh.style.CMS) # or ATLAS/LHCb2

h, bins = np.histogram(np.random.random(1000))
fig, ax = plt.subplots()
hep.histplot(h, bins)
mh.histplot(h, bins)

Will feature binder

Expand Down
32 changes: 16 additions & 16 deletions examples/Examples.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"import mplhep as hep"
"import mplhep as mh"
]
},
{
Expand Down Expand Up @@ -52,11 +52,11 @@
"y = np.random.normal(512, 112, 240)\n",
"z = np.random.normal(0.5, 0.1, 240)\n",
"\n",
"plt.style.use([hep.style.ROOT, hep.style.firamath])\n",
"plt.style.use([mh.style.ROOT, mh.style.firamath])\n",
"\n",
"f, ax = plt.subplots()\n",
"ax.scatter(x, y, c=z, label=\"XSX\")\n",
"hep.cms.label(loc=0)\n",
"mh.cms.label(loc=0)\n",
"\n",
"plt.show()"
]
Expand Down Expand Up @@ -98,16 +98,16 @@
"axs = axs.flatten()\n",
"\n",
"axs[0].set_title(\"Default\", fontsize=18)\n",
"hep.histplot(h, bins, ax=axs[0])\n",
"mh.histplot(h, bins, ax=axs[0])\n",
"\n",
"axs[1].set_title(\"Plot Edges\", fontsize=18)\n",
"hep.histplot(h, bins, edges=True, ax=axs[1])\n",
"mh.histplot(h, bins, edges=True, ax=axs[1])\n",
"\n",
"axs[2].set_title(\"Plot Errorbars\", fontsize=18)\n",
"hep.histplot(h, bins, yerr=np.sqrt(h), ax=axs[2])\n",
"mh.histplot(h, bins, yerr=np.sqrt(h), ax=axs[2])\n",
"\n",
"axs[3].set_title(\"Filled Histogram\", fontsize=18)\n",
"hep.histplot(h, bins, histtype=\"fill\", ax=axs[3])\n",
"mh.histplot(h, bins, histtype=\"fill\", ax=axs[3])\n",
"\n",
"\n",
"plt.tight_layout()\n",
Expand Down Expand Up @@ -149,17 +149,17 @@
"axs = axs.flatten()\n",
"\n",
"axs[0].set_title(\"Default Overlay\", fontsize=18)\n",
"hep.histplot([h, 1.5 * h], bins, ax=axs[0])\n",
"mh.histplot([h, 1.5 * h], bins, ax=axs[0])\n",
"\n",
"axs[1].set_title(\"Default Overlay w/ Errorbars\", fontsize=18)\n",
"hep.histplot([h, 1.5 * h], bins, yerr=[np.sqrt(h), np.sqrt(1.5 * h)], ax=axs[1])\n",
"mh.histplot([h, 1.5 * h], bins, yerr=[np.sqrt(h), np.sqrt(1.5 * h)], ax=axs[1])\n",
"\n",
"\n",
"axs[2].set_title(\"Automatic Errorbars\", fontsize=18)\n",
"hep.histplot([h, 1.5 * h], bins, yerr=True, ax=axs[2])\n",
"mh.histplot([h, 1.5 * h], bins, yerr=True, ax=axs[2])\n",
"\n",
"axs[3].set_title(\"With Labels\", fontsize=18)\n",
"hep.histplot([h, 1.5 * h], bins, yerr=True, ax=axs[3], label=[\"First\", \"Second\"])\n",
"mh.histplot([h, 1.5 * h], bins, yerr=True, ax=axs[3], label=[\"First\", \"Second\"])\n",
"\n",
"axs[3].legend(fontsize=16)\n",
"\n",
Expand Down Expand Up @@ -202,16 +202,16 @@
"axs = axs.flatten()\n",
"\n",
"axs[0].set_title(\"Default\", fontsize=18)\n",
"hep.histplot([h, 1.5 * h], bins, stack=True, ax=axs[0])\n",
"mh.histplot([h, 1.5 * h], bins, stack=True, ax=axs[0])\n",
"\n",
"axs[1].set_title(\"Plot Edges\", fontsize=18)\n",
"hep.histplot([h, 1.5 * h], bins, edges=True, stack=True, ax=axs[1])\n",
"mh.histplot([h, 1.5 * h], bins, edges=True, stack=True, ax=axs[1])\n",
"\n",
"axs[2].set_title(\"Plot Errorbars\", fontsize=18)\n",
"hep.histplot([h, 1.5 * h], bins, yerr=[np.sqrt(h), np.sqrt(h)], stack=True, ax=axs[2])\n",
"mh.histplot([h, 1.5 * h], bins, yerr=[np.sqrt(h), np.sqrt(h)], stack=True, ax=axs[2])\n",
"\n",
"axs[3].set_title(\"Filled Histogram\", fontsize=18)\n",
"hep.histplot([1.5 * h, h], bins, histtype=\"fill\", stack=True, ax=axs[3])\n",
"mh.histplot([1.5 * h, h], bins, histtype=\"fill\", stack=True, ax=axs[3])\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
Expand Down Expand Up @@ -256,7 +256,7 @@
"H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))\n",
"\n",
"fig, ax = plt.subplots()\n",
"hep.hist2dplot(H, xedges, yedges, labels=True);"
"mh.hist2dplot(H, xedges, yedges, labels=True);"
]
},
{
Expand Down
13 changes: 9 additions & 4 deletions src/mplhep/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@

# Get styles directly, also available within experiment helpers.
# Get helper functions
from . import alice, atlas, cms, comp, dune, label, lhcb, plot
from . import comp, label, plot
from . import exp_alice as alice
from . import exp_atlas as atlas
from . import exp_cms as cms
from . import exp_dune as dune
from . import exp_lhcb as lhcb
from . import styles as style
from ._tools import Config
from ._version import version as __version__ # noqa: F401
Expand All @@ -25,7 +30,7 @@
plot_model,
plot_two_hist_comparison,
)
from .label import add_text, save_variations, savelabels
from .label import add_text, append_text, save_variations, savelabels
from .plot import (
append_axes,
box_aspect,
Expand Down Expand Up @@ -53,9 +58,8 @@
# Configs
rcParams = Config(
label=Config(
text=None,
data=None,
kind=None,
supplementary=None,
year=None,
lumi=None,
llabel=None,
Expand All @@ -80,6 +84,7 @@
"add_text",
"alice",
"append_axes",
"append_text",
"atlas",
"box_aspect",
"cms",
Expand Down
Loading
Loading