2

I am writing a package that, among other things, does some plotting with matplotlib. I'd like all the plots generated using the package to follow a custom style, defined in a matplorlibrc file. Currently, I am using a (minimal) package structure as follows:

pkg
├── pkg
│   ├── afile.py
│   ├── __init__.py
│   └── _mpl_config
│       └── style.mplstyle
└── setup.py

The following is near the top of afile.py:

import os
import matplotlib.pyplot as plt

plt.style.use(os.path.join(
    os.path.split(__file__)[0], '_mpl_config', 'style.mplstyle'))

# some plotting routines...

In __init__.py:

import pkg.afile

After doing a pip install, I can use a plotting routine with

import pkg
pkg.<plotting_routine>

So far this seems to work, as the above line instructs matplotlib to use the style found at <path_to_pkg>/pkg/_mpl_config/style.mplstyle. However, I'm not sure if this is robust enough (i.e. will be used in all import cases) or if there is a better way.

jomobro
  • 35
  • 1
  • 5
  • Does this answer your question? [How to read a (static) file from inside a Python package?](https://stackoverflow.com/a/20885799/3279716) See the second example in that answer. – Alex May 28 '21 at 14:57

1 Answers1

1

You should not overwrite the matplotlib style with your package, because the end user may want to use its own style in other parts of its code. Instead, use a context manager each time you want to make a plot:

with mpl.style.context(os.path.join(os.path.split(__file__)[0], '_mpl_config', 'style.mplstyle')):
    # Do your plotting here
Diego Palacios
  • 1,096
  • 6
  • 22