Adjust exponent text after setting scientific limits on matplotlib axis

后端 未结 5 993
旧时难觅i
旧时难觅i 2020-12-05 16:13

At the moment if I set matplotlib y axis ticklabels to scientific mode it gives me an exponent at the top of the y axis of the form 1e-5

I\'d like to ad

5条回答
  •  余生分开走
    2020-12-05 16:47

    Building on @KirstieJane's solution, I found a sightly better way, wich also works without having to call tight_layout, and in particular, also works for figures using constrained_layout. Calling ax.get_tightbbox(renderer) is all that is necessary for setting the text. Here is an MWE:

    import sys
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.tight_layout import get_renderer
    from matplotlib.backends.backend_qt5agg import \
        FigureCanvasQTAgg as FigureCanvas
    # from matplotlib.transforms import Bbox
    # from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    from PyQt5.QtWidgets import QDialog, QApplication, QGridLayout
    
    
    class MainWindow(QDialog):
        def __init__(self):
            super().__init__()
            fig, ax = plt.subplots(constrained_layout=True)
            canvas = FigureCanvas(fig)
            lay = QGridLayout(self)
            lay.addWidget(canvas)
            self.setLayout(lay)
    
            image = np.random.uniform(10000000, 100000000, (100, 100))
            image_artist = ax.imshow(image)
            colorbar = fig.colorbar(image_artist)
            colorbar.ax.ticklabel_format()
            renderer = get_renderer(fig)
            colorbar.ax.get_tightbbox(renderer)
            colorbar.ax.yaxis.offsetText.set_visible(False)
            offset_text = colorbar.ax.yaxis.get_offset_text()
            exp = offset_text.get_text().split('e')[1].replace('+', '')
            colorbar.ax.set_ylabel(rf'Parameter [U${{\times}}10^{{{exp}}}$]')
    
            canvas.draw_idle()
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        GUI = MainWindow()
        GUI.show()
        sys.exit(app.exec_())
    

    For a thorough discussion of the solution, see my answer here.

提交回复
热议问题