Home > front end >  How to set matplotlib parameters using a file
How to set matplotlib parameters using a file

Time:08-31

I am making a series of plots from several different scripts. I want to use the 'seaborn-bright' style with some minor changes.

How can I efficiently apply the style and changes to all scripts, before creating the plots, without having to copy/paste the template to every script? Something where I can import the style changes and automatically apply to every plot generated in the script.

I guess I could create the plots and the apply a function to the fig, ax to clean them up, but I'd rather define things at the start.

I also could save the style sheet for seaborn-bright and edit the definitions, but that seems tedious and it seems like there should be a better way.

Example:

import matplotlib.pyplot as plt

### Template for all plots
### How do I have this as a separate file and just call/execute?
plt.style.use("seaborn-bright")
plt.rcParams["figure.figsize"] = (3,2)
plt.rcParams["figure.dpi"] = 120
plt.rcParams["xtick.direction"] = "in"
# lots of other little things

### Example plot in a stand-alone script
fig, ax = plt.subplots(1, 1)
ax.plot([0, 1], [0, 1])
ax.plot([0.2, 0.8], [0.2, 0.2])
ax.plot([0.2, 0.8], [0.4, 0.4])

CodePudding user response:

You can place all these features in a separate py file that is located in the same directory as your main code file (ipynb) and then call it to run with %run -i Parameters.py or whatever you want to call it. You can even put the py file in another folder, you just have to make the current working directory where that file is located with os.chdir('Path/to/Parameters.py')

My Parameters.py file:

plt.style.use("seaborn-bright")
plt.rcParams["figure.figsize"] = (3,2)
plt.rcParams["figure.dpi"] = 120
plt.rcParams["xtick.direction"] = "in"

My Main.ipynb code:

import matplotlib.pyplot as plt
%run -i Parameters.py

plt.plot([1,2,3])

Output:

enter image description here

~~ EDIT for Main.py instead of Main.ipynb ~~

If you are working with two py files, the best thing to do would be to just use import YourParametersFileName like any other module. Unfortunately, you will have to import your other modules in both py files (e.g. import matplotlib.pyplot as plt will have to be in both files). But Python is great in not using extra resources to double import those modules (as it sees that they are already loaded, but it does need the plt variable definition for both for example). So, name the parameters file something unique (as to not mess with your python environment by naming it like Numpy.py or something) and you should be good to go:

Parameters.py code:

import matplotlib.pyplot as plt
plt.style.use("seaborn-bright")
plt.rcParams["figure.figsize"] = (3,2)
plt.rcParams["figure.dpi"] = 120
plt.rcParams["xtick.direction"] = "in"

Main.py code:

import matplotlib.pyplot as plt
import Parameters

plt.plot([1,2,3])
plt.show()
  • Related