Python Forum
Tuple Unpacking with graphs in matplotlib - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Tuple Unpacking with graphs in matplotlib (/thread-2540.html)



Tuple Unpacking with graphs in matplotlib - smw10c - Mar-23-2017

I hope you are all having a good day. I am currently taking a MOOC on Python. We went over a bit of code in matplotlib:

Fig=plt.figure()
Fig,axes=plt.subplots(nrows=1,ncols=2)

The instructor said that "fig, axes" is a way of doing tuple unpacking. I know what tuple unpacking is, however, I don't understand it in this context. If someone could please explain it would be greatly appreciated.


RE: Tuple Unpacking with graphs in matplotlib - zivoni - Mar-23-2017

plt.subplots() returns tuple containg figure object and arrray of axis objects (if atleast one of nrows or ncols is > 1).

When you want plot with two subplots in one row, you use fig, axes = plt.subplots(1,2), unpacking assigns figure into fig and axis array into axes. After that you can use axes to access specified subplots, while fig is used to control entire figure. Simple example:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2, 2, 400)
fig, axes = plt.subplots(1,2)
axes[0].plot(x, x**2)
axes[1].plot(x, x**3)
fig.savefig('boo.png', dpi=200)
[Image: OOKQKp8.png]


RE: Tuple Unpacking with graphs in matplotlib - smw10c - Mar-23-2017

(Mar-23-2017, 04:51 PM)zivoni Wrote: plt.subplots() returns tuple containg figure object and arrray of axis objects (if atleast one of nrows or ncols is > 1). When you want plot with two subplots in one row, you use fig, axes = plt.subplots(1,2), unpacking assigns figure into fig and axis array into axes. After that you can use axes to access specified subplots, while fig is used to control entire figure. Simple example:
 import numpy as np import matplotlib.pyplot as plt x = np.linspace(-2, 2, 400) fig, axes = plt.subplots(1,2) axes[0].plot(x, x**2) axes[1].plot(x, x**3) fig.savefig('boo.png', dpi=200) 
[Image: OOKQKp8.png]

That was exceedingly helpful. Thank you!