有效的解决方案
由于单独替换每个轴的方法比使用简单函数更多的输入,最有效的方法是创建一个具有相应功能的python文件myhacks.py
def pcolormesh(ax, *args, **kwargs):
p = ax.pcolormesh(*args, **kwargs)
p.set_edgecolor('face')
p.set_linewidth(0.2)
return p
并在需要改进版本的pcolormesh时使用它
import matplotlib.pyplot as plt
import myhacks as m
# ..other imports
fig, ax = plt.subplots()
m.pcolormesh(ax, other_arguments)
这也适用于已经创建的文件,其中人们只需搜索替换“ax.pcolormesh(”with“m.pcolormesh(ax,”)(如果需要,可以使用正则表达式来表示其他可能的轴名称).
学术解决方案
当然可以将matplotlib.axes.Axes子类化以包含所需的函数.由于没有真正的好处,除了知道如何做,我称之为“学术解决方案”.
所以,我们再次为自定义类创建一个文件myhacks.py,将自定义类注册为matplotlib的投影,
from matplotlib.axes import Axes
from matplotlib.projections import register_projection
class MyAxes(Axes):
name = 'mycoolnewaxes'
def pcolormesh(self,*args, **kwargs):
p = Axes.pcolormesh(self,*args, **kwargs)
p.set_edgecolor('face')
p.set_linewidth(0.2)
return p
register_projection(MyAxes)
并通过导入它并使用投影创建轴来使用它:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import myhacks as m
fig = plt.figure()
gs = GridSpec(2,1)
ax = fig.add_subplot(gs[0,0], projection='mycoolnewaxes')
z = np.random.rand(10,13)
ax.pcolormesh(z)
plt.show()