如何防止Matplotlib使用非默认样式时覆盖自定义rcParams?
Great question—this is a common gotcha with Matplotlib styles, since applying a style resets most rcParams to the style’s defaults. Here are a few straightforward ways to ensure your custom figure size (or any other rcParam) sticks:
1. Apply the Style First, Then Override Your Params
The simplest approach is to load the style first, then set your custom rcParams afterward. Your settings will overwrite the style’s default values:
import matplotlib.pyplot as plt # Load the fivethirtyeight style plt.style.use('fivethirtyeight') # Now set your custom figure size (or any other rcParam) plt.rcParams['figure.figsize'] = [20, 8] # Create your plot—this will use the style + your custom size plt.plot([1,2,3], [4,5,6]) plt.show()
2. Merge Your Custom Params with the Style
If you want to permanently modify the style to include your settings (so you don’t have to re-set them every time), update the style’s dictionary before using it:
import matplotlib.pyplot as plt # Get the fivethirtyeight style's rcParams fivethirtyeight_style = plt.style.library['fivethirtyeight'] # Add your custom figure size to the style's params fivethirtyeight_style.update({'figure.figsize': [20, 8]}) # Use the modified style plt.style.use(fivethirtyeight_style) # Your plots will now automatically use the style + your custom size plt.plot([1,2,3], [4,5,6]) plt.show()
3. Use a Context Manager for Temporary Overrides
If you only want your custom settings to apply to specific plots (without changing the global style), use Matplotlib’s context manager. You can even pass both the style and your custom params in one go:
import matplotlib.pyplot as plt # Use the style and your custom params only within this block with plt.style.context(['fivethirtyeight', {'figure.figsize': [20, 8]}]): plt.plot([1,2,3], [4,5,6]) plt.show() # Outside the context, plots will use the default style (or whatever was set before) plt.plot([1,2,3], [6,5,4]) plt.show()
All three methods will ensure your figure size (or any other custom rcParam) isn’t overwritten by the style. The first method is the most straightforward for most cases, while the context manager is perfect if you need different settings for different plots.
内容的提问来源于stack exchange,提问作者Nicky Feller

