Page 118 - Informatics_Practices_Fliipbook_Class12
P. 118
The syntax for subplot() is as follows:
subplot(rowNum, colNum, FigNum)
Here, rowNum represents the number of rows in the subplot grid, colNum represents the number of columns, and
FigNum represents the figure number or the position of the current subplot.
In the next example, we visualize this by creating three subplots. Each subplot represents a different variable plotted
against the days of the week as shown in Fig 3.17. In the first, second, and third subplot (Program 2), daily temperature,
daily humidity, and daily air quality index is plotted for days of a week. In the last two lines of the code snippet, we have
used plt.tight_layout() function which helps to improve the spacing between subplots, and plt.show() to
display the figure containing the subplots.
Program 2: Plotting daily temperature, daily humidity, and daily air quality index for days of a week in different
subplots of the same graph
01 import matplotlib.pyplot as plt
02
03 # Example data for a week (7 days)
04 days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
05 temperature = [28, 30, 31, 29, 27, 29, 26] # in degrees Celsius
06 humidity = [60, 58, 55, 62, 63, 59, 61] # in percentage
07 airQuality = [50, 45, 48, 55, 60, 52, 58] # air quality index
08
09 # Create a fig. with three subplots
10 plt.fig(figsize=(10, 12))
11
12 # Subplot 1: Daily Temperature
13 plt.subplot(3, 1, 1) # 3 rows, 1 column, subplot 1
14 plt.plot(days, temperature, marker='o', label='Temperature')
15 plt.xlabel('Day')
16 plt.ylabel('Temperature (°C)')
17 plt.title('Subplot 1: Daily Temperature')
18 plt.legend()
19
20 # Subplot 2: Daily Humidity
21 plt.subplot(3, 1, 2) # 3 rows, 1 column, subplot 2
22 plt.plot(days, humidity, marker='o', label='Humidity')
23 plt.xlabel('Day')
24 plt.ylabel('Humidity (%)')
25 plt.title('Subplot 2: Daily Humidity')
26 plt.legend()
27
28 # Subplot 3: Daily Air Quality Index
29 plt.subplot(3, 1, 3) # 3 rows, 1 column, subplot 3
30 plt.plot(days, airQuality, marker='o', label='Air Quality Index')
31 plt.xlabel('Day')
32 plt.ylabel('Air Quality Index')
33 plt.title('Subplot 3: Daily Air Quality Index')
34 plt.legend()
35
36 # Adjust layout and show the plots
37 plt.tight_layout()
38 plt.show()
104 Touchpad Informatics Practices-XII

