全局设置刻度数。X轴,Y轴,颜色条。

4

对于字体大小,我发现在matplotlib的几乎每个坐标轴上,5个刻度是最美观的。我还喜欢修剪x轴上最小的刻度,以避免重叠的刻度标签。因此,对于我制作的几乎每个图,我都会使用以下代码。

from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator

plt.imshow( np.random.random(100,100) )
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 7, prune = 'lower') )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 6) )
cbar = plt.colorbar()
cbar.locator = MaxNLocator( nbins = 6)
plt.show()

是否有一个rc设置可以使用,使得我的x轴、y轴和色条的默认定位器默认为上面带有x轴修剪选项的MaxNLocator?

3个回答

3
为什么不编写一个自定义模块myplotlib,将这些默认值设置为您所需要的值呢?
import myplt
myplt.setmydefaults()

全局rc设置可能会破坏依赖这些设置不被修改的其他应用程序。


我喜欢那个想法。就像一个继承matplotlib的自定义类?但是我不确定myplt.setmydefaults会是什么样子。 - ncRubert
其实这不是一个类,只是一个调用 plt.whatever 的方法罢了。 - Has QUIT--Anony-Mousse

2
matplotlib.ticker.MaxNLocator类有一个属性可用于设置默认值:
default_params = dict(nbins = 10,
                      steps = None,
                      trim = True,
                      integer = False,
                      symmetric = False,
                      prune = None)

例如,在您的脚本开头加上这行代码,每当轴对象使用 MaxNLocator 时就会创建5个刻度。
from matplotlib.ticker import *
MaxNLocator.default_params['nbins']=5

然而,默认定位器是matplotlib.ticker.AutoLocator,基本上使用硬编码参数调用MaxNLocator,因此上述内容没有全局效果,除非进行进一步的修改。要将默认定位器更改为MaxNLocator,我能找到的最好方法是用自定义方法覆盖matplotlib.scale.LinearScale.set_default_locators_and_formatters
import matplotlib.axis, matplotlib.scale 
def set_my_locators_and_formatters(self, axis):
    # choose the default locator and additional parameters
    if isinstance(axis, matplotlib.axis.XAxis):
        axis.set_major_locator(MaxNLocator(prune='lower'))
    elif isinstance(axis, matplotlib.axis.YAxis):
        axis.set_major_locator(MaxNLocator())
    # copy & paste from the original method
    axis.set_major_formatter(ScalarFormatter())
    axis.set_minor_locator(NullLocator())
    axis.set_minor_formatter(NullFormatter())
# override original method
matplotlib.scale.LinearScale.set_default_locators_and_formatters = set_my_locators_and_formatters

这样做的好处是可以为X和Y轴刻度分别指定不同的选项。

1

根据Anony-Mousse的建议

创建一个名为myplt.py的文件

#!/usr/bin/env python
# File: myplt.py

from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator

plt.imshow( np.random.random(100,100) )
plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 7, prune = 'lower') )
plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 6) )
cbar = plt.colorbar()
cbar.locator = MaxNLocator( nbins = 6)
plt.show()

在您的代码或ipython会话中

import myplt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接