3

I'm using Matplotlib creating a number of plot functions (to be put in a module). The different functions refer to different types of plots, and I would like to have different "style sheets" (i.e. different settings for lines, markers, axes etc) depending on the plot type. However, I run into problem when trying to set predefined Matplotlib styles using the pyplot.style.use() function from within the plotting functions. Setting it in the main script works, but then I can't have different styles for different plots.

So, this code sets the style as I want

# A plot function
def my_plot(ax, xd, yd):
    '''Create a plot'''

    ax.scatter(xd, yd) 

# Main Script 
import numpy as np
import matplotlib.pyplot as plt 

# Set plot style sheet in main script
plt.style.use('ggplot')

fig, ax = plt.subplots(1)

x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)

sc = my_plot(ax, x, y)

plt.show()

However, the below does not, although the rc parameter settings have been changed after the function call, so running the script again from within python changes the style of the figure accordingly.

# A plot function
def my_plot(ax, xd, yd):
    '''Create a plot'''

    # Set plot style sheet in function
    plt.style.use('ggplot')

    ax.scatter(xd, yd) 

# Main Script 
import numpy as np
import matplotlib.pyplot as plt 

fig, ax = plt.subplots(1)

x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)

sc = my_plot(ax, x, y)

plt.show()

1 Answer 1

3

You can use temporary styling within your function:

with plt.style.context(('ggplot')):
    ax.scatter(xd, yd)

This won't change the line widths of axes because it only applies the style to what is within the block. To style the axes (e.g. line widths) you need to use a style sheet before the subplots call (as you did in your first example), or wrap that in a temporary style.

As far as I know style sheets can't be retroactively applied to objects that have already been created. To do that, you would need to loop over the properties you want changed and set them explicitly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.