I have a program with an emedded figure that also shows a colorbar with custom tick labels. However, the automatic resizing of the figure cuts off part of the tick labels. This wouldn't be too bad if I could simply manually resize the window a bit so that everything is shown again. But, when you resize the window, the figure stretches in such a way that there is a large empty space created on the left side while the tick labels on the right can still not be completely seen unless you stretch the window unnecessarily wide. How can I change this behaviour? Below is an example. As you can see I already tried a few things but none of them worked.
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
FigureCanvasQTAgg as FigureCanvas
import matplotlib.ticker as mticker
from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout
from PyQt5.QtCore import QSize
class MathTextSciFormatter(mticker.Formatter):
def __init__(self, fmt="%1.1e"):
self.fmt = fmt
def __call__(self, x, pos=None):
s = self.fmt % x
decimal_point = '.'
positive_sign = '+'
tup = s.split('e')
significand = tup[0].rstrip(decimal_point)
sign = tup[1][0].replace(positive_sign, '')
exponent = tup[1][1:].lstrip('0')
if exponent:
exponent = '10^{%s%s}' % (sign, exponent)
if significand and exponent:
s = r'%s{\times}%s' % (significand, exponent)
else:
s = r'%s%s' % (significand, exponent)
return "${}$ W/m${{}}^2$".format(s)
class Test(QDialog):
def __init__(self):
super().__init__()
self.lay = QGridLayout(self)
self.fig, self.ax = plt.subplots()
# self.ax.set_anchor('SW')
# self.ax.set_position([0, 0, 0, 0])
# self.fig.tight_layout()
# self.ax.margins(0, 0)
self.canvas = FigureCanvas(self.fig)
self.lay.addWidget(self.canvas)
self.resize(QSize(380, 290))
self.setMaximumHeight(290)
self.image = np.reshape(np.random.randint(0, 1000, 10000), (100, 100))
self.image_artist = self.ax.imshow(self.image)
self.colorbar = self.fig.colorbar(self.image_artist)
self.colorbar.ax.yaxis.set_major_formatter(
MathTextSciFormatter()
)
if __name__ == '__main__':
app = QApplication(sys.argv)
test = Test()
test.show()
sys.exit(app.exec_())