Matplotlib样式表未生效:twinx()是否为问题诱因?
twinx() Hey there! It’s super common to run into style quirks when using twinx() for dual y-axis plots—let’s break down why your styles aren’t applying and how to fix it.
Why Your Styles Might Not Be Working
First off, let’s clear up a key point: Matplotlib styles need to be loaded before you create any figures or axes. If you’re setting the style after calling plt.subplots(), it won’t affect the already-existing axes (including the twin one you create later). Also, while twinx() creates a new axes that shares the x-axis, some style properties don’t automatically carry over to the new y-axis, which can make it look like the style isn’t working.
Fixes to Get Your Styles Applying Properly
1. Load the Style First—Before Any Plotting
This is the most common fix. Move your style load call to the top of your script, right after importing Matplotlib. Here’s how your code should look:
import pickle import numpy as np import matplotlib.pyplot as plt # Load your desired style BEFORE creating the figure plt.style.use('seaborn-v0_8') # Swap this for 'ggplot', 'fivethirtyeight', etc. with open("acc.pkl", "rb") as a: acc = pickle.load(a) with open("loss.pkl", "rb") as b: loss = pickle.load(b) x = np.array(range(100)) fig, graph_1 = plt.subplots() points_1 = np.array(acc) graph_1.plot(x, points_1) # Remove explicit colors like 'b' to let the style handle it # Create your twin axis graph_2 = graph_1.twinx() points_2 = np.array(loss) graph_2.plot(x, points_2) plt.show()
2. Make the Twin Axis Match the Style
If some elements (like y-tick colors or the right spine) still don’t match, you can explicitly set them using the style’s built-in parameters. This ensures consistency:
# After creating graph_2 graph_2.tick_params(axis='y', colors=plt.rcParams['ytick.color']) graph_2.spines['right'].set_color(plt.rcParams['axes.edgecolor'])
This pulls values directly from the style you loaded, so everything stays in sync.
3. Ditch Explicit Color Overrides
If you’re hardcoding colors (like 'b' for blue) in your plot() calls, you’re overriding the style’s default color cycle. Remove those explicit color codes to let the style do its job.
4. Confirm Your Style is Available
Double-check that the style you’re trying to use actually exists on your system. Run this quick check:
print(plt.style.available)
This lists all installed styles—if yours isn’t there, you might need to install a style package (like seaborn for the seaborn styles) or use a built-in one.
Why twinx() Seems to Be the Culprit
When you call twinx(), it creates a separate axes object for the second y-axis. If your style was loaded after the first axes was created, this twin axes won’t inherit the style settings. Even if you load the style first, some axes-specific properties (like y-axis ticks) are unique to each axes, so you might need to tweak them manually to match.
内容的提问来源于stack exchange,提问作者S.Mandal

