Plotting with Matplotlib

Plotting with Matplotlib

Matplotlib (https://matplotlib.org/) is a library for 2D plotting based on NumPy. Here are some basic examples. More examples can be found in the official documentation (https://matplotlib.org/2.0.2/gallery.html and https://matplotlib.org/2.0.2/examples/index.html)

Plotting with Matplotlib: Plots with Common X-axis but di erent Y-axis :
Using twinx()

In this example, we will plot a sine curve and a hyperbolic sine curve in the same plot with a common x-axis having different y-axis. This is accomplished by the use of twinx() command.

Plotting tutorials in Python
Adding Multiple plots by twin x axis
Good for plots having different y axis range
Separate axes and figure objects
replicate axes object and plot curves
use axes to set attributes
Note:
Grid for second curve unsuccessful : let me know if you find it! :(
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2.0*np.pi, 101)
y = np.sin(x)
z = np.sinh(x)
separate the figure object and axes object
from the plotting object
fig, ax1 = plt.subplots()
Duplicate the axes with a different y axis
and the same x axis
ax2 = ax1.twinx() # ax2 and ax1 will have common x axis and different y axis
plot the curves on axes 1, and 2, and get the curve handles curve1, = ax1.plot(x, y, label="sin", color='r')
curve2, = ax2.plot(x, z, label="sinh", color='b')
Make a curves list to access the parameters in the curves curves = [curve1, curve2]
add legend via axes 1 or axes 2 object.
one command is usually sufficient
ax1.legend() # will not display the legend of ax2
ax2.legend() # will not display the legend of ax1 ax1.legend(curves, [curve.get_label() for curve in curves])
ax2.legend(curves, [curve.get_label() for curve in curves]) # also valid
Global figure properties
plt.title("Plot of sine and hyperbolic sine")
plt.show()

Plotting with Matplotlib: Plots with common Y-axis and di erent X-axis using twiny()

In this example, a plot with curves having common y-axis but different x-axis is demonstrated using twiny() method. Also, some additional features such as the title, legend, labels, grids, axis ticks and colours are added to the plot.

Plotting tutorials in Python
Adding Multiple plots by twin y axis
Good for plots having different x axis range
Separate axes and figure objects
replicate axes object and plot curves
use axes to set attributes
import numpy as np
import matplotlib.pyplot as plt
y = np.linspace(0, 2.0*np.pi, 101)
x1 = np.sin(y)
x2 = np.sinh(y)
values for making ticks in x and y axis ynumbers = np.linspace(0, 7, 15) xnumbers1 = np.linspace(-1, 1, 11) xnumbers2 = np.linspace(0, 300, 7)
separate the figure object and axes object
from the plotting object
fig, ax1 = plt.subplots()
Duplicate the axes with a different x axis
and the same y axis
ax2 = ax1.twiny() # ax2 and ax1 will have common y axis and different x axis
plot the curves on axes 1, and 2, and get the axes handles curve1, = ax1.plot(x1, y, label="sin", color='r') curve2, = ax2.plot(x2, y, label="sinh", color='b')
Make a curves list to access the parameters in the curves curves = [curve1, curve2]
add legend via axes 1 or axes 2 object.
one command is usually sufficient
ax1.legend() # will not display the legend of ax2
ax2.legend() # will not display the legend of ax1
ax1.legend(curves, [curve.get_label() for curve in curves]) ax2.legend(curves, [curve.get_label() for curve in curves]) # also valid
x axis labels via the axes
ax1.set_xlabel("Magnitude", color=curve1.get_color())
ax2.set_xlabel("Magnitude", color=curve2.get_color())

y axis label via the axes

ax1.set_ylabel("Angle/Value", color=curve1.get_color())
ax2.set_ylabel("Magnitude", color=curve2.get_color()) # does not work
ax2 has no property control over y axis
y ticks - make them coloured as well
ax1.tick_params(axis='y', colors=curve1.get_color())
ax2.tick_params(axis='y', colors=curve2.get_color()) # does not work
ax2 has no property control over y axis
x axis ticks via the axes
ax1.tick_params(axis='x', colors=curve1.get_color())
ax2.tick_params(axis='x', colors=curve2.get_color())

set x ticks

ax1.set_xticks(xnumbers1)
ax2.set_xticks(xnumbers2)

set y ticks

ax1.set_yticks(ynumbers)
ax2.set_yticks(ynumbers) # also works
Grids via axes 1 # use this if axes 1 is used to
define the properties of common x axis
ax1.grid(color=curve1.get_color())
To make grids using axes 2
ax1.grid(color=curve2.get_color())
ax2.grid(color=curve2.get_color())
ax1.xaxis.grid(False)

Global figure properties

plt.title(“Plot of sine and hyperbolic sine”)
plt.show()

Plotting with Matplotlib: A Simple Plot in Matplotlib

This example illustrates how to create a simple sine curve using Matplotlib

Plotting tutorials in Python
Launching a simple plot
import numpy as np
import matplotlib.pyplot as plt
angle varying between 0 and 2pi x = np.linspace(0, 2.0np.pi, 101)
y = np.sin(x) # sine function
plt.plot(x, y)
plt.show()

Adding more features to a simple plot : axis labels, title, axis ticks, grid, and legend

In this example, we take a sine curve plot and add more features to it; namely the title, axis labels, title, axis ticks, grid and legend.

Plotting tutorials in Python
Enhancing a plot
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2.0*np.pi, 101)
y = np.sin(x)
values for making ticks in x and y axis xnumbers = np.linspace(0, 7, 15) ynumbers = np.linspace(-1, 1, 11)
plt.plot(x, y, color='r', label='sin') # r - red colour plt.xlabel("Angle in Radians") plt.ylabel("Magnitude")
plt.title("Plot of some trigonometric functions")
plt.xticks(xnumbers)
plt.yticks(ynumbers)
plt.legend()
plt.grid()
plt.axis([0, 6.5, -1.1, 1.1]) # [xstart, xend, ystart, yend] plt.show()

Making multiple plots in the same figure by superimposition similar to MATLAB

In this example, a sine curve and a cosine curve are plotted in the same figure by superimposing the plots on top of each other.

Plotting tutorials in Python
Adding Multiple plots by superimposition
Good for plots sharing similar x, y limits
Using single plot command and legend
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2.0*np.pi, 101)
y = np.sin(x)
z = np.cos(x)
values for making ticks in x and y axis xnumbers = np.linspace(0, 7, 15) ynumbers = np.linspace(-1, 1, 11)
plt.plot(x, y, 'r', x, z, 'g') # r, g - red, green colour plt.xlabel("Angle in Radians") plt.ylabel("Magnitude")
plt.title("Plot of some trigonometric functions")
plt.xticks(xnumbers)
plt.yticks(ynumbers)
plt.legend(['sine', 'cosine'])
plt.grid()
plt.axis([0, 6.5, -1.1, 1.1]) # [xstart, xend, ystart, yend] plt.show()

Making multiple Plots in the same figure using plot superimposition with separate plot commands

Similar to the previous example, here, a sine and a cosine curve are plotted on the same figure using separate plot commands. This is more Pythonic and can be used to get separate handles for each plot.

Plotting tutorials in Python
Adding Multiple plots by superimposition
Good for plots sharing similar x, y limits
Using multiple plot commands
Much better and preferred than previous
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2.0*np.pi, 101)
y = np.sin(x)
z = np.cos(x)
values for making ticks in x and y axis xnumbers = np.linspace(0, 7, 15) ynumbers = np.linspace(-1, 1, 11)
plt.plot(x, y, color='r', label='sin') # r - red colour plt.plot(x, z, color='g', label='cos') # g - green colour plt.xlabel("Angle in Radians") plt.ylabel("Magnitude")
plt.title("Plot of some trigonometric functions")
plt.xticks(xnumbers)
plt.yticks(ynumbers)
plt.legend()
plt.grid()
plt.axis([0, 6.5, -1.1, 1.1]) # [xstart, xend, ystart, yend] plt.show()

Learn More

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment