Changes to rcParams affect external code

Issue #16 resolved
Val created an issue

Minimal reproducible example:

import matplotlib as mpl
mpl.rcParams['font.family'] = 'serif'
import matplotlib.pyplot as plt

# uncomment this and Foo will be sans-serif
#import SchemDraw

plt.plot([0], [0], label='Foo')
plt.legend()

plt.show()

This happens because the library sets rcParams globally inside schemdraw.py and also inside Drawing.draw(). I think this can be worked around using a temporary matplotlib style instead, but I haven’t looked into it too much. I’ll be glad to make a PR if needed 🙂

Comments (8)

  1. cdelker repo owner

    I agree matplotlib’s style context managers would be the way to fix this, using rc_context. Would be nice if the rc dictionary could be changed by the user in case they don’t like the fonts/styles I thought looked nice. Looks like schemdraw sets some rcParams on import, but also in the draw() method.

    Feel free to submit a PR if you need it soon, I may not have a chance to work on it for a few weeks.

  2. Val reporter

    I tried using rc_context however it turns out that, according to this issue, fonts are chosen later down the drawing process, which means fonts in rc_context get ignored in IPython and friends.

    I realized this after reading through a lot of the code, and I’m beginning to think we may not need rc_context after all. Currently, the only rcParams that are changed here are

    # Global
    mpl.rcParams['figure.subplot.left']   = 0.05
    mpl.rcParams['figure.subplot.bottom'] = 0.05
    mpl.rcParams['figure.subplot.right']  = 0.95
    mpl.rcParams['figure.subplot.top']    = 0.90
    mpl.rcParams['font.family'] = 'sans-serif'
    mpl.rcParams['mathtext.fontset'] = 'stixsans'
    mpl.rcParams['mathtext.default'] = 'regular'
    
    # Drawing.draw
    mpl.rcParams['font.size'] = self.fontsize
    mpl.rcParams['font.family'] = self.font
    

    Of these, figure.* can be specified manually with plt.subplots_adjust() when needed. Font family and font size already seem to be set individually for each segment. That leaves mathtext.* which, again, could and probably should be left to the user to preserve styling across other figures as well.

  3. Val reporter

    @cdelker I uploaded a PR with the code changes. If there’s anything else I should change/add, let me know.

  4. Log in to comment