SciencePlots科研繪圖

SciencePlots科研繪圖

在這裏插入圖片描述

簡介

使用Python作爲核心開發工具的機器學習和深度學習研究者自然會希望使用Matplotlib進行科研圖表的繪製,但是Matplotlib默認的樣式並不適合科研論文的出版,而SciencePlots就是爲此定製的一系列科研繪圖樣式庫,可以繪製很合適科研圖表。

安裝

具體的安裝教程可以參考該項目Github開源地址,我這裏簡述一下。

PIP快速安裝

使用下面的第一個命令安裝最新版,第二個命令直接從PIP官方源下載安裝,要落後最新版一個版本。

pip install git+https://github.com/garrettj403/SciencePlots.git
pip install SciencePlots

手動安裝

上面的PIP安裝會自動下載所有的*.mplstyle文件並將其放在當前環境的matplotlib的stylelib文件夾下,這個步驟也可以手動完成。Clone官方倉庫到本地,將其中style文件夾下的所有以mplstyle爲後綴的文件拷貝到matplotlib的資源目錄下的stylelib文件夾,獲得matplotlib資源目錄可以通過下面的代碼段獲取。

import matplotlib
print(matplotlib.get_configdir())

獲得該目錄後直接訪問,新建stylelib文件夾(若有則不需要新建),將所有*.mplstyle文件放到該目錄下即可。

在這裏插入圖片描述

使用

在所有的樣式中,science.mplstyle爲最核心的樣式,使用該樣式的方法和matpl切換樣式的方法一致。

import matplotlib.pyplot as plt
plt.style.use('science')

當然,也可以指定多個樣式,如下面這段代碼中,ieee樣式在某些部分會覆蓋science樣式以達到繪圖需求。

import matplotlib.pyplot as plt
plt.style.use(['science','ieee'])

上面這幾種方法都是對整個腳本生效的,想要對某個部分繪圖的代碼生效,則只需要使用with語句進行上下文管理即可。

with plt.style.context(['science', 'ieee']):
    plt.figure()
    plt.plot(x, y)
    plt.show()

案例

下面三個圖是science樣式、science+ieee以及science+ieee+grid樣式的效果,在樣式中加入no-latex以禁用Latex字體渲染,這是因爲science樣式默認採用Latex渲染,若沒有安裝Latex或者考慮到其比較耗時,禁用即可。


science

science+ieee

science+ieee+grid

上述效果的代碼如下。

import numpy as np
import matplotlib.pyplot as plt


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


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

with plt.style.context(['science', 'no-latex']):
    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.set(xlabel='Voltage (mV)')
    ax.set(ylabel='Current (μA)')
    ax.autoscale(tight=True)
    fig.savefig('fig1.png', dpi=300)

with plt.style.context(['science', 'ieee', 'no-latex']):
    fig, ax = plt.subplots()
    for p in [10, 20, 50]:
        ax.plot(x, model(x, p), label=p)
    ax.legend(title='Order')
    ax.set(xlabel='Voltage (mV)')
    ax.set(ylabel='Current (μA)')
    ax.autoscale(tight=True)
    fig.savefig('fig2.png', dpi=300)

with plt.style.context(['science','ieee', 'grid', 'no-latex']):
    fig, ax = plt.subplots()
    for p in [10, 20, 50]:
        ax.plot(x, model(x, p), label=p)
    ax.legend(title='Order')
    ax.set(xlabel='Voltage (mV)')
    ax.set(ylabel='Current (μA)')
    ax.autoscale(tight=True)
    fig.savefig('fig3.png', dpi=300)

補充說明

如果有論文裏繪圖想要使用Matplotlib又不想花費太多精力定製繪圖樣式,SciencePlots是很不錯的選擇,已經有不少發表的文章採用該庫了,感興趣可以嘗試一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章