garrettj403/SciencePlots

[Feature] siunitx mplstyle

开放

#101 创建于 2023年7月1日

 (3 条评论) (1 个反应) (0 位负责人)Python (658 个派生)batch import
enhancementgood first issue

仓库指标

星标
 (6,088 个星标)
PR 合并指标
 (平均合并 17小时 3分钟) (30 天内合并 2 个 PR)

描述

Hello, hope you are doing great.

There is this package siunitx which allows for a better usage of units in latex. This allows for different usage of units inside latex and to be more consistent in their use inside and outside of equations.

I believe it would be easy to implement in SciencePlots as an additional mplstyle.

Proposal

For this it could be easy to create a latex-siunitx.mplstyle inside the misc folder with the line

text.latex.preamble :\usepackage{amsmath} \usepackage{amssymb} \usepackage{siunitx}

Example

import numpy as np
import matplotlib.pyplot as plt
import scienceplots

x = np.linspace(0.75, 1.25, 201)

def model(x, p):
    return x ** (2 * p + 1) / (1 + x ** (2 * p))

With the current implementation units would be like

pparam = dict(xlabel='Voltage (mV)', ylabel=r'Current ($\mu$A)')

with plt.style.context(['science']):
    fig, ax = plt.subplots()
    for p in [10, 15, 20, 30, 50, 100]:
        ax.plot(x, model(x, p), label=p)
    ax.legend(title='Order')
    ax.autoscale(tight=True)
    ax.set(**pparam)
    fig.savefig('fig01.png', dpi=300)
    plt.close()

fig01

with the new implementation it would change to

pparam = dict(xlabel=r'Voltage (\si{\milli\volt})', ylabel=r'Current (\si{\micro\ampere})')

with plt.style.context(['science','latex-siunitx']):
    fig, ax = plt.subplots()
    for p in [10, 15, 20, 30, 50, 100]:
        ax.plot(x, model(x, p), label=p)
    ax.legend(title='Order')
    ax.autoscale(tight=True)
    ax.set(**pparam)
    fig.savefig('fig01-siunitx.png', dpi=300)
    plt.close()

fig01-siunitx

Caveats

The only problem I seem to find with this is that if another style changes the text.latex.preamble line it would clash. It would be a problem for nature, russian-font, turkish-font, latex-sans, pgf and sans. Also it wouldn't work with styles that don't use latex like notebook.

Maybe this could be worked around in some way.

Best, Fran

贡献者指南