Create a plot with broken axis in Python using Matplotlib

Here in this article, we are going to plot a graph or figure with the broken axis using the Python matplotlib library. In an earlier article, we learned about how to plot a graph or figure but we didn’t mention anything about the broken axis.

Before we go forward, let me tell you what is broken exis in brief.

In broken axis, all pieces of information are provided in the name itself. The axis which is broken or skipped numbers from number line is known as the Broken axis. Below is given an example of a broken axis in the form of the figure.

Broken Axis in Matplotlib

 

Plotting of broken axis using Python matplotlib with examples

In this article, the plotted graph has the axis which is broken, for example, we set the axis limit from 1 to 8, and we broke the axis from 5 – 5.5 then the axis which we broke will look like the skipped numbers from the number lines of that particular axis which we broke. Let’s understand with some examples:-

Example 1:-

import matplotlib.pyplot as plt
from brokenaxes import brokenaxes
import numpy as np

fig = plt.figure(figsize=(6,4))
baxes = brokenaxes(xlims=((0,0.1),(0.4,0.7)), ylims=((-1,.7),(0.79,1)), hspace=.05)
x = np.linspace(0,1,50)
baxes.plot(x,np.sin(15*x),label="sin")
baxes.plot(x,np.cos(15*x),label="cos")
baxes.legend(loc="best")
plt.show()

Output:-

The output figure of our code is given below:

plot broken axis in Python Matplotlib

In the above example, we had imported the required modules for the plotting of the graph with the broken axes. The required modules are matplotlib, numpy, and brokenaxes. Then we created an object named fig and set the figure size.

After that, we created another object named baxes and set the x-limits and y-limits and then stored the numpy array in variable x using numpy.linspace() and then we plotted the two graphs of sine and cosine and used the plt.show() to show the graph. We used the legend function to show the additional information regarding the graph that which graph is of sine or cosine graph.

Example 2:-

import matplotlib.pyplot as plt 
from brokenaxes import brokenaxes 
import numpy as np 
fig = plt.figure(figsize=(6,4)) 
baxes = brokenaxes(xlims=((-2,3),(5,8)), ylims=((0,8),(9.5,21)), hspace=.1) 
X = np.array([3,-1,0,4,5,-2,7]) 
Y = x**2
Z = x**3
baxes.plot(X,Y,label="squared") 
baxes.plot(X,Z,label="cubed") 
baxes.legend(loc="best")
plt.plot()
plt.show()

Output:-

Broken axis plot in matplotlib Python

In this example, we followed all the previous example steps but in this example, we created a numpy array and stored it in a variable named X and then we created two-variable Y and Z and established the relation between them, Y=Xand Z=X3. Then we plotted our graph using plt.plot() and showed our graph using plt.show().

You may also read this article:-

Leave a Reply

Your email address will not be published. Required fields are marked *