簡體   English   中英

Matplotlib,全局設置滴答數。 X軸,Y軸,彩條

[英]Matplotlib, globally set number of ticks. X-axis, Y-axis, colorbar

對於我喜歡使用的字體大小,我發現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軸和colorbar的默認定位器默認是上面的MaxNLocator,x軸上有prune選項?

你為什么不寫一個自定義模塊myplotlib來設置你喜歡的默認值?

import myplt
myplt.setmydefaults()

全局rc設置可能會破壞依賴於這些設置的其他應用程序不被修改。

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刻度指定不同的選項。

正如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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM