What I want to do is:
- Start the figure with two subplots (stacked one above another)
- Press 'x' on keyboard to: resize figure, and show a third plot on the right
- Press 'x' again to: resize figure back to original, and hide the third plot (without leaving space for the third plot).
With the example code below, I got to this (matplotlib 3.1.2, Python3 in MINGW64, Windows 10):
As it is shown on the gif - even in the starting state, there is some empty space on the right (since I didn't know any better way how to solve this, other than define a grid). Then, when the figure window extends/resizes, it is not "exactly" resized so it fits the third plot.
How can I achieve a toggling of this third plot, such that when it is hidden, there is no extra empty space on the right - and when it is shown, the figure extends exactly so the third plot fits (including margins) (EDIT: and the existing/initial two plots do not change in size)?
The code:
#!/usr/bin/env python3
import matplotlib
print("matplotlib.__version__ {}".format(matplotlib.__version__))
import matplotlib.pyplot as plt
import numpy as np
default_size_inch = (9, 6)
showThird = False
def onpress(event):
global fig, ax1, ax2, ax3, showThird
if event.key == 'x':
showThird = not showThird
if showThird:
fig.set_size_inches(default_size_inch[0]+3, default_size_inch[1], forward=True)
plt.subplots_adjust(right=0.85) # leave a bit of space on the right
ax3.set_visible(True)
ax3.set_axis_on()
else:
fig.set_size_inches(default_size_inch[0], default_size_inch[1], forward=True)
plt.subplots_adjust(right=0.9) # default
ax3.set_visible(False)
ax3.set_axis_off()
fig.canvas.draw()
def main():
global fig, ax1, ax2, ax3
xdata = np.arange(0, 101, 1) # 0 to 100, both included
ydata1 = np.sin(0.01*xdata*np.pi/2)
ydata2 = 10*np.sin(0.01*xdata*np.pi/4)
fig = plt.figure(figsize=default_size_inch, dpi=120)
ax1 = plt.subplot2grid((3,3), (0,0), colspan=2, rowspan=2)
ax2 = plt.subplot2grid((3,3), (2,0), colspan=2, sharex=ax1)
ax3 = plt.subplot2grid((3,3), (0,2), rowspan=3)
ax3.set_visible(False)
ax3.set_axis_off()
ax1.plot(xdata, ydata1, color="Red")
ax2.plot(xdata, ydata2, color="Khaki")
fig.canvas.mpl_connect('key_press_event', lambda event: onpress(event))
plt.show()
# ENTRY POINT
if __name__ == '__main__':
main()