Python | Marking Regions across Horizontal Axis in Plot

In this tutorial, we are going to mark regions across the horizontal axis in a plot for better distinguishing it from the rest of the plot.
Submitted by Anuj Singh, on August 01, 2020

It is a small plotting/data visualization technique used often and has a good application in areas of Physics Plotting. The following example shows an example of region marking by using inbuilt functions in Matplotlib.

Python | Marking Regions across Horizontal Axis in Plot (1)

Python | Marking Regions across Horizontal Axis in Plot (2)

Python code for marking regions across horizontal axis in plot

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 4 * np.pi - 3, 0.01)
y = np.sin(x)

for i in range(len(y)):
    if y[i] <= 0:
        y[i] = 0

plt.figure(figsize=(6,3))
plt.plot(x, y, color='black')
threshold = 0.75
plt.axhline(threshold, color='purple', lw=2, alpha=0.7)
plt.fill_between(x, 0, 1, where=y > threshold, color='purple', alpha=0.5)
plt.xlabel('Time(s)')
plt.ylabel('Magnitude')
plt.axhline(y=0, color='grey')
plt.grid()
plt.title('AC Wave')

plt.figure(figsize=(6,7))
plt.subplot(211)
plt.plot(x, y, color='black')
plt.xlabel('Time(s)')
plt.ylabel('Magnitude')
plt.axhline(y=0, color='grey')
plt.grid()
plt.title('AC Wave')

plt.subplot(212)
plt.plot(x, y, color='black')
threshold = 0.75
plt.axhline(threshold, color='purple', lw=2, alpha=0.7)
plt.fill_between(x, 0, 1, where=y > threshold, color='purple', alpha=0.5)
plt.xlabel('Time(s)')
plt.ylabel('Magnitude')
plt.axhline(y=0, color='grey')
plt.grid()
plt.suptitle('Comparing Plots')

Output:

Output is as figure





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.