matplotlib轴标签的偏移量的因数和偏移

matplotlib轴标签的偏移量的因数和偏移

本文介绍了matplotlib轴标签的偏移量的因数和偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在matplotlib的轴刻度标签上,有两种可能的偏移量:因子移位:

在右下角 1e-8 将是一个因子",而 1.441249698e1 将是一个移位".

这里有很多答案展示了如何操作两者:

  • 请记住,这种情节是不准确的,您不应该在向其他人提交的任何报告中使用它,因为他们不知道如何解释它.

    On the axes tick labels in matplotlib, there are two kinds of possible offsets: factors and shifts:

    In the lower right corner 1e-8 would be a "factor" and 1.441249698e1 would be a "shift".

    There are a lot of answers here showing how to manipulate both of them:

    I would like to just remove the shifts and can't seem to figure out how to do it. So matplotlib should only be allowed to scale my axis, but not to move the zero point. Is there a simple way to achieve this behaviour?

    解决方案

    You can fix the order of magnitude to show on the axis as shown in this question. The idea is to subclass the usual ScalarFormatter and fix the order of magnitude to show. Then setting the useOffset to False will prevent showing some offset, but still shows the factor.

    Thwe format "%1.1f" will show only one decimal place. Finally using a MaxNLocator allows to set the maximum number of ticks on the axes.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker
    
    class OOMFormatter(matplotlib.ticker.ScalarFormatter):
        def __init__(self, order=0, fformat="%1.1f", offset=False, mathText=True):
            self.oom = order
            self.fformat = fformat
            matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,useMathText=mathText)
        def _set_orderOfMagnitude(self, nothing):
            self.orderOfMagnitude = self.oom
        def _set_format(self, vmin, vmax):
            self.format = self.fformat
            if self._useMathText:
                self.format = '$%s$' % self.format
    
    x = [0.6e-8+14.41249698, 3.4e-8+14.41249698]
    y = [-7.7e-11-1.110934954e-2, -0.8e-11-1.110934954e-2]
    
    fig, ax = plt.subplots()
    ax.plot(x,y)
    
    y_formatter = OOMFormatter(-2, "%1.1f")
    ax.yaxis.set_major_formatter(y_formatter)
    x_formatter = OOMFormatter(1, "%1.1f")
    ax.xaxis.set_major_formatter(x_formatter)
    
    ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
    ax.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
    
    plt.show()
    

    Keep in mind that this plot is inaccurate and you shouldn't use it in any kind of report you hand to other people as they wouldn't know how to interprete it.

    这篇关于matplotlib轴标签的偏移量的因数和偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:51