'How to batch setting of plot properties with multiple parameters in matplotlib?

a normal version:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())

# setting
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
                            rotation=30, fontsize='small')
ax.set_xlabel('Stages')
ax.set_title('My first matplotlib plot')

a batch version setting verison:

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(1000).cumsum())

props = {
    'xticks': [0, 250, 500, 750, 1000],
    'title': 'My first matplotlib plot',
    'xlabel': 'Stages'
}
ax.set(**props)

but how can I add labels = ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],rotation=30, fontsize='small') into props?
It seems this function has some parameters and dict has just one value for the key, nested dict seems don't work.



Solution 1:[1]

Your example and some personal settings

with plt.rc_context({#Change the color of the axes
                     'axes.edgecolor':'darkslategray', 
                     #Change the color of both the tick and the label
                     'xtick.color':'darkslategray', 
                     'ytick.color':'darkslategray',
                     #Change axes label and title location
                     'xaxis.labellocation': 'left',
                     'yaxis.labellocation': 'top',
                     'axes.titlelocation': 'left',
                     #Change axes label and title size
                     'axes.labelsize': 'medium',
                     'axes.titlesize': 'x-large',
                     #Hide top and right axes
                     'axes.spines.top': False,
                     'axes.spines.right': False}):
    # Temporary rc parameters in effect
    fig = plt.figure(figsize=(8,3.5))
    ax = fig.add_subplot(1, 1, 1)
    #Set ticks position/labes, title, xlabel and ylabel
    _sets = {'xticks': [0, 250, 500, 750, 1000],
             'xticklabels': ['one', 'two', 'three', 'four', 'five'], 
             'title': 'My first matplotlib plot', 
             'xlabel': 'Stages', 
             'ylabel': 'Cumulative Sum'}
    ax.set(**_sets)
    #Plot data
    ax.plot(np.random.randn(1000).cumsum())

What are the parameters you can use with rc_context?

# rcParams keys list
from pylab import rcParams
rcParams.keys()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jprzd