Matplotlib,全局设置滴答数。 X轴,Y轴,彩条

时间:2012-05-03 18:58:27

标签: python matplotlib

对于我喜欢使用的字体大小,我发现5个刻度是matplotlib中几乎每个轴上最令人愉悦的刻度数。我也喜欢修剪 沿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轴和颜色栏的默认定位器默认为上面的MaxNLocator,x轴上带有剪枝选项?

3 个答案:

答案 0 :(得分:3)

为什么不编写一个自定义模块myplotlib来设置这些默认值?

import myplt
myplt.setmydefaults()

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

答案 1 :(得分:2)

matplotlib.ticker.MaxNLocator类有一个可用于设置默认值的属性:

default_params = dict(nbins = 10,
                      steps = None,
                      trim = True,
                      integer = False,
                      symmetric = False,
                      prune = None)

例如,脚本开头的这一行将在每次{1}}轴对象使用时创建5个刻度。

MaxNLocator

但是,默认定位器是from matplotlib.ticker import * MaxNLocator.default_params['nbins']=5 ,基本上使用硬连线参数调用matplotlib.ticker.AutoLocator,这样上面的内容就没有全局效果而没有进一步的黑客攻击。

要将默认定位器更改为MaxNLocator,我能找到的最好的方法是使用自定义方法覆盖MaxNLocator

matplotlib.scale.LinearScale.set_default_locators_and_formatters

这具有很好的副作用,能够为X和Y刻度指定不同的选项。

答案 2 :(得分: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
相关问题