Skill - Multiple Plots in a same subplot using Matplotlib
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Introduction to Matplotlib plotting library
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
Matplotlib is a plotting library in the scipy ecosystem of libraries.
In this post we will try to understand how to create multiple plots in the same subplot
Please make sure that you covered the post on basics
Example
import matplotlib.pyplot as plt
# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()
# plot some data
ax.plot([0,4,8,12], [6,8,4,2])
# plot again
ax.plot([0,3,9,12,15,18], [2,1,9,6,4,3])
# print plot
plt.show()
So just by calling plot
function on a single axes handle, we can add any number of plots to a single subplot.
More styled example
This example is the same as above, but adds some extra styling.
Please make sure you covered the styling plots post in order to understand this code.
import matplotlib.pyplot as plt
# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()
# set plot title
ax.set_title('Multiple plots example')
# set x and y labels
ax.set_xlabel('this is X-axis')
ax.set_ylabel('this is Y-axis')
# plot some data and get the line artist object in return
la1, = ax.plot([0,4,8,12], [6,8,4,2], color='#de689f')
# set label to line artist object for legend
la1.set_label('First Plot')
# plot again and get the line artist object in return
la2, = ax.plot([0,3,9,12,15,18], [2,1,9,6,4,3], color='#a155b9')
# set label to line artist object for legend
la2.set_label('Second Plot')
# set a marker style
la2.set_marker('o')
# enable legends
ax.legend()
# print plot
plt.show()
Video
You can the video on this post here
Online Interpreter
Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://pynative.com/online-python-code-editor-to-execute-python-code/
Multiple plots example
Styled multiple plots example
References
- plot function API - https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html
- Examples gallery - https://matplotlib.org/gallery/index.html
Comments
Post a Comment