使用matplotlib进行绘图时,经常遇到个问题,就是总是要花大量代码对绘图的格式进行设置。虽然可以将同一类绘图的代码保存以后使用,但是看着这么长一串用来设置格式就很不爽。
一、matplotlib自带风格
matlotlib中,自带了许多不同的风格。
通过以下方法可以查看自带风格:
from matplotlib import pyplot as plt
查看 Matplotlib 可用绘图风格
print(plt.style.available)
输出结果如下:
关于这些风格的预览,可以在官方文档中查看:matplotlib Style sheets reference。
加上一行代码就能轻松改变matplotlib的风格:
plt.style.use('name')
不过说实话这玩意根本没啥用。
二、Science Plots
某位哈佛大学的野生博士不忍重复绘图之苦,于是自己开发了science,ieee,nature等期刊的matplotlib绘图补充包。下载和使用的详情见:Science Plots Github。
下面是对应该补充包的一个使用例:
""" An example of the 'science' theme. """
import numpy as np
import matplotlib.pyplot as plt
def model(x, p):
return x ** (2 * p + 1) / (1 + x ** (2 * p))
x = np.linspace(0.75, 1.25, 201)
with plt.style.use(['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.set(xlabel='Voltage (mV)')
ax.set(ylabel='Current ($\mu$A)')
ax.autoscale(tight=True)
fig.savefig('figures/fig1.pdf')
fig.savefig('figures/fig1.jpg', dpi=300)
然后便能直接绘制science风格的图了!
感觉似乎很 牛逼的样子?但是我根本发不了science也不用投ieee啊!
三、自定义matplotlib风格
在安装了science plot包后,我们可以在目录中:C:\Users\user name.matplotlib\stylelib创建一个.mplstyle文件自定义matplotlib风格。
以下是我写的一个mystyle.mplstyle文件:
Use serif fonts 使用新罗马字体,加粗。
font.serif : Times New Roman
font.family : serif
font.weight : bold
Use LaTeX for math formatting #不使用LaTeX。
text.usetex : False
text.latex.preamble : \usepackage{amsmath}
Set color cycle: blue, green, yellow, red, violet, gray #设置循环颜色
axes.prop_cycle : cycler('color', ['0C5DA5', '00B945', 'FF9500', 'FF2C00', '845B97', '474747', '9e9e9e'])
Set default figure size #设置图片尺寸
#figure.figsize : 3.5,2.625
#Set default plot #线宽
lines.linewidth : 2
#Set legend style #设置图例
legend.loc : 'best'
legend.frameon : False
legend.fontsize : 12
#Set axes #设置框
axes.linewidth : 1.5
axes.labelweight : bold
#Set labels #设置坐标字体
axes.labelsize: 14
xtick.labelsize: 12
ytick.labelsize: 12
#Set save #图片分辨率
savefig.dpi : 600
使用mystyle前作图:
使用mystyle后作图:
Original: https://blog.csdn.net/weixin_51982763/article/details/126979230
Author: 薛定谔的青蛙
Title: matplotlib自定义风格
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/767201/
转载文章受原作者版权保护。转载请注明原作者出处!