Data Visualization with Matplotlib

18 / 20

Getting Stared with Matplotlib - Subplots in Matplotlib

At times, we might want to display more than one chart at a time. We can achieve this by using subplots.

INSTRUCTIONS
  • First, import Pyplot

    import matplotlib.<< your code goes here >> as plt
    
    • Now we will create a sample plot

      plt.plot([1,4,7], [1,4,7])

    It basically plots lines that go thru (1,1), (4,4), (7,7) which is a straight line at 45 degrees. We did this to demonstrate that creating a subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary.

    • Now, in the same cell as before, we will create a subplot using the subplot() function with the top plot of a grid with 2 rows and 1 column. Since this subplot will overlap the first, the plot (and its axes) previously created, will be removed

      plt.<< your code goes here >>(2,1,1) plt.plot(range(12)) plt.subplot(2,1,2, facecolor='red') plt.plot(range(12)) plt.show()

    The third line creates a second subplot with red background.

    • You can add and insert a plot in the same figure by adding another axes object in the same figure canvas. The matplotlib.figure module contains the Figure class. It is a top-level container for all plot elements. The Figure object is instantiated by calling the figure() function of the pyplot module. You can create it as follows:

      import matplotlib.pyplot as plt import numpy as np import math x = np.arange(0, math.pi*2, 0.09) fig=plt.figure() axes1 = fig.add_axes([0.1, 0.1, 0.9, 0.9]) axes2 = fig.add_axes([0.62, 0.62, 0.3, 0.3]) y = np.sin(x) axes1.plot(x, y, 'b') axes2.plot(x,np.cos(x),'r') axes1.set_title('sine') axes2.set_title("cosine") plt.show()

    Here, axes1 is the main axes, and axes2 is the inset axes. You can test with different values to move and resize the charts.

Get Hint See Answer


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...