Foundation of Data Science: Unit V: Data Visualization

Subplots

Matplotlib | Data Visualization

Subplots mean groups of axes that can exist in a single matplotlib figure. subplots() function in the matplotlib library, helps in creating multiple layouts of subplots.

Subplots

• Subplots mean groups of axes that can exist in a single matplotlib figure. subplots() function in the matplotlib library, helps in creating multiple layouts of subplots. It provides control over all the individual plots that are created.

• subplots() without arguments returns a Figure and a single Axes. This is actually the simplest and recommended way of creating a single Figure and Axes.

fig, ax = plt.subplots()

ax.plot(x,y)

ax.set_title('A single plot')

Output:

• There are 3 different ways (at least) to create plots (called axes) in matplotlib. They are:plt.axes(), figure.add_axis() and plt.subplots()

• plt.axes(): The most basic method of creating an axes is to use the plt.axes function. It takes optional argument for figure coordinate system. These numbers represent [bottom, left, width, height] in the figure coordinate system, which ranges from 0 at the bottom left of the figure to 1 at the top right of the figure.

• Plot just one figure with (x,y) coordinates: plt.plot(x, y).

•  By calling subplot(n,m,k), we subdidive the figure into n rows and m columns and specify that plotting should be done on the subplot number k. Subplots are numbered row by row, from left to right.

importmatplotlib.pyplotasplt

importnumpyasnp

frommathimportpi

plt.figure(figsize=(8,4)) # set dimensions of the figure

x=np.linspace (0,2*pi,100)

foriinrange(1,7):

plt.subplot(2,3,i)# create subplots on a grid with 2 rows and 3 columns

plt.xticks([])# set no ticks on x-axis

plt.yticks([])# set no ticks on y-axis

plt.plot(np.sin(x), np.cos(i*x))

plt.title('subplot'+'(2,3,' + str(i)+')')

plt.show()

Output:


Foundation of Data Science: Unit V: Data Visualization : Tag: : Matplotlib | Data Visualization - Subplots