How to move the y axis scale factor to the position next to the y axis label?

后端 未结 2 1337
庸人自扰
庸人自扰 2020-11-29 07:06

I have some data plotted which I force to scientific notation to powers of 10 (instead of exponential). Heres a snippet of the code:

import matplotlib.ticker         


        
2条回答
  •  眼角桃花
    2020-11-29 07:23

    You may set the offset to invisible, such that it does not appear in its original position.

    ax.yaxis.offsetText.set_visible(False)
    

    You may then get the offset from the formatter an update the label with it

    offset = ax.yaxis.get_major_formatter().get_offset()
    ax.yaxis.set_label_text("original label" + " " + offset)
    

    such that it appears inside the label.

    The following automates this using a class with a callback, such that if the offset changes, it will be updated in the label.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.ticker as mticker
    
    class Labeloffset():
        def __init__(self,  ax, label="", axis="y"):
            self.axis = {"y":ax.yaxis, "x":ax.xaxis}[axis]
            self.label=label
            ax.callbacks.connect(axis+'lim_changed', self.update)
            ax.figure.canvas.draw()
            self.update(None)
    
        def update(self, lim):
            fmt = self.axis.get_major_formatter()
            self.axis.offsetText.set_visible(False)
            self.axis.set_label_text(self.label + " "+ fmt.get_offset() )
    
    
    x = np.arange(5)
    y = np.exp(x)*1e-6
    
    fig, ax = plt.subplots()
    ax.plot(x,y, marker="d")
    
    formatter = mticker.ScalarFormatter(useMathText=True)
    formatter.set_powerlimits((-3,2))
    ax.yaxis.set_major_formatter(formatter)
    
    lo = Labeloffset(ax, label="my label", axis="y")
    
    
    plt.show()
    

提交回复
热议问题