分享一个Matplotlib扩展工具SciencePlots,一行代码绘制science、nature、ieee等要求的图形。
安装
- 安装SciencePlots
# 直接从PyPI安装
pip install SciencePlots
- 安装latex
如果latex未安装,会报错:RuntimeError: Failed to process string with tex because latex could not be found 。根据电脑系统选择,方法参考:https://github.com/garrettj403/SciencePlots/wiki/FAQ#installing-latex
使用方法
SciencePlots使用方法和matplotlib默认style调用一样,详细参考👉:matplotlib-rcParams及绘图风格(style)设置详解
- plt.style.use整个图设置
import matplotlib.pyplot as plt
import scienceplots #导入scienceplots
plt.style.use('science') #使用scienceplots中的science主题
- with plt.style.context临时设置
with plt.style.context('science') #临时使用scienceplots中的science主题
- 多个主题联合使用
上面是单个主题设置,也可以多个主题联合使用,
plt.style.use(['science', 'vibrant']) #联合使用science和vibrant主题
- 更多主题
可以单个使用,可以多个联合使用,
[['science'], ['science', 'no-latex'], ['science', 'ieee'],
['science', 'ieee', 'std-colors'], ['science', 'nature'],
['science', 'scatter'], ['science', 'high-vis'],
['dark_background', 'science', 'high-vis'], ['science', 'notebook'],
['science', 'bright'], ['science', 'vibrant'], ['science', 'muted'],
['science', 'retro'], ['science', 'grid'], ['science', 'high-contrast'],
['science', 'light'], ['science', 'no-latex', 'cjk-tc-font'],
['science', 'no-latex',
'cjk-sc-font'], ['science', 'no-latex', 'cjk-jp-font'],
['science', 'no-latex', 'cjk-kr-font'], ['science', 'russian-font'],
['science', 'turkish-font']]
demo
展示部分,
import numpy as np
import matplotlib.pyplot as plt
import scienceplots
# SciencePlots部分样式列表
styles = [['science', 'grid'], ['science'], ['high-vis'],
['science', 'ieee', 'std-colors'], ['science', 'ieee'],
['science', 'nature'], ['science', 'vibrant']]
num_styles = len(styles)
# 模拟绘图数据
def model(x, p):
return x**(2 * p + 1) / (1 + x**(2 * p))
x = np.linspace(0.75, 1.25, 201)
for i, style in enumerate(styles):
plt.figure(figsize=(6, 6), dpi=200)
with plt.style.context(style): #一行代码,临时使用scienceplots一种主题
ax = plt.gca()
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_xlabel('Voltage (mV)')
ax.set_ylabel('Current ($\mu$A)')
ax.set_title(f'Style: {", ".join(style)}')
plt.tight_layout()
plt.show()
效果很赞,
- ['science', 'grid']
- ['science']主题
- ['high-vis']主题
- ['science', 'ieee', 'std-colors']主题
- ['science', 'ieee']主题
- ['science', 'nature']主题
- ['science', 'vibrant'] 主题
进一步学习👇:一行代码science、nature图表!一行代码实现science、nature、iehttps://mp.weixin.qq.com/s?__biz=MzUwOTg0MjczNw==&mid=2247523775&idx=1&sn=e250cb92fbcbac3948bd7c45681d9193&chksm=f90ed9e1ce7950f7f563f132676287ca41b42d9dd9cfcd70331ebfa6eb267824f78c6bd51592&token=413843954&lang=zh_CN#rd