Top Posts
Types of JDBC drivers
C++ Program to implements Constructor Overloading
C++ Program to implements Constructor
C++ Program to calculate the area using classes
C++ Class Program to Store and Display Employee...
Operator Overloading of Decrement — Operator
Postfix Increment ++ Operator Overloading
Prefix Increment ++ operator overloading with return type
Prefix ++ Increment Operator Overloading with no return...
JDBC Architecture
TECHARGE
  • HOME
  • BLOGS
  • TUTORIALS
    • ALL TUTORIALS
    • PROGRAMMING TUTORIALS
      • JAVA TUTORIALS
      • C++ TUTORIAL
      • C PROGRAMMING TUTORIALS
      • PYTHON TUTORIAL
      • KNOWLEDGE MANAGEMENT TUTORIALS
      • DATA STRUCTURE AND ALGORITHM TUTORIALS
      • PROGRAMMING EXAMPLES
        • CPP EXAMPLES
        • JAVA EXAMPLES
        • C++ GRAPHICS PROGRAM
    • PROJECTS
      • PYTHON PROJECTS
      • SWIFT PROJECT
    • PPROGRAMMING QUIZ
    • DBMS TUTORIALS
    • COMPUTER NETWORK TUTORIALS
    • COMPUTER NETWORK SECURITY TUTORIALS
    • E COMMERCE TUTORIALS 
    • AWS TUTORIAL
    • INTERNET OF THINGS
    • CHEATSHEET
  • MORE
    • JOBS AND INTERNSHIPS
    • INTERVIEW PREPARATION
    • TECH BOOK
    • TECH NEWS
    • INSTAGRAM GALLERY
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • WEB STORIES
    • CONTACT US
  • WRITE +
  • ABOUT US
Matplotlib Library

Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib

by Prateek Kashyap November 29, 2022
written by Prateek Kashyap 4 comments
Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib
Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib

Table of Contents

  • Histograms
      • Output:
    • PathPatch object
      • Output:
    • Three-dimensional plotting
      • Output:
    • Streamplot
      • Output:

Histograms

The hist() function generates histograms automatically and returns the bin counts or probabilities. This demo shows a few optional characteristics in addition to the basic histogram:

  • Setting the number of data bins.
  • The parameter of density, Which normalises the height of the bin so that the histogram integral is 1.
  • The resulting histogram is an approximation of the probability density function.
  • Setting the face color of the bars. Setting the opacity (alpha value).
import matplotlib import numpy as np import matplotlib.pyplot as plt np.random.seed(19680801) # example data mu = 100 # mean of distribution sigma = 15 # standard deviation of distribution x = mu + sigma * np.random.randn(437) num_bins = 50 fig, ax =plt.subplots() # the histogram of the data n, bins, patches = ax.hist(x, num_bins, density=True) # add a 'best fit' line y = ((1 / (np.sqrt(2 * np.pi) *sigma))* np.exp(-0.5* (1 / sigma *(bins - mu))**2)) ax.plot(bins, y, '--') ax.set_xlabel('Smarts') ax.set_ylabel('Probability density') ax.set_title(r'Histogram of IQ: $\mu-1000$, $\sigma=15$') # Tweak spacing to prevent clipping of ylabel fig.tight_layout() plt.show()
Code language: PHP (php)

Output:

Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib

PathPatch object

In Matplotlib, you can use the matplotlib. path module to add arbitrary paths:

import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, ax = plt.subplots() Path = mpath.Path path_data = [ (Path.MOVETO, (1.58, -2.57)), (Path.CURVE4, (0.35, -1.1)), (Path.CURVE4, (-1.75, 2.0)), (Path.CURVE4, (0.375, 2.0)), (Path.LINETO, (0.85, 1.15)), (Path.CURVE4, (2.2, 3.2)), (Path.CURVE4, (3, 0.05)), (Path.CURVE4, (2.0, -0.5)), (Path.CLOSEPOLY, (1.58, -2.57)),] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5) ax.add_patch(patch) # plot control points and connecting Lines x, y = zip(*path.vertices) line = ax.plot(x, y, 'go-' ) ax.grid() ax.axis('equal') plt.show()
Code language: PHP (php)

Output:

Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib

Three-dimensional plotting

The mplot3d toolkit (see Getting Started and 3D Plotting) supports simple surface-inclusive 3d graphs with wireframe, scatter and bar charts.

import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) # Make data. X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) # A StrMethodFormatter is used automatically ax.zaxis.set_major_formatter('{x:.02f}') # Add a colour bar that maps the colours to the values. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
Code language: PHP (php)

Output:

Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib

Streamplot

For displaying 2D vector fields, a stream plot or streamline plot is used. A few features of the streamplot function are shown in this example:

Varying the color along a streamline. Varying the density of streamlines. Varying the line width along a streamline. Controlling the starting points of streamlines. Streamlines skipping masked regions and NaN values.

import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # Creating dataset w = 3 Y, X = np.mgrid[-w:w:100j, -w:w:100j] U = -1 - X**2 + Y V = 1 + X - Y**2 speed = np.sqrt(U**2 + V**2) fig = plt.figure(figsize =(20, 16)) gs = gridspec.GridSpec(nrows = 3, ncols = 2, height_ratios =[1, 1, 2]) # Create a mask mask = np.zeros(U.shape, dtype = bool) mask[40:60, 40:60] = True U[:20, :20] = np.nan U = np.ma.array(U, mask = mask) ax = fig.add_subplot(gs[2:, :]) ax.streamplot(X, Y, U, V, color ='r') ax.set_title('Streamplot with Masking') ax.imshow(~mask, extent =(-w, w, -w, w), alpha = 0.5, interpolation ='nearest', cmap ='gray', aspect ='auto') ax.set_aspect('equal') plt.tight_layout() plt.show()
Code language: PHP (php)

Output:

Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib

Hope you enjoyed this article on PathPatch,3D plotting & StreamPlot in Matplotlib, Happy Programming 🙂

histogramObjectThree-dimensionalPathPatchPlottingStreamplot
Share 6 FacebookTwitterLinkedinRedditWhatsappTelegramEmail
Prateek Kashyap

Studies Computer Science Engineering at Bundelkhand institute of engineering and technology, Jhansi. love programming, specialization in C, C++ and Python programming languages.

previous post
Python | Ellipse, Pie Charts, Tables and Scatter Plot in Matplotlib
next post
Modes of Transmission in Network

You may also like

Python | GUI Widgets, Date Tick labels, Polar Plots, and XKCD-style sketch...

Python: Plots, Images, Contour and Pseudocolor in Matplotlib

Python | Ellipse, Pie Charts, Tables and Scatter Plot in Matplotlib

Python | Pyplot in Matplotlib Tutorial

Python | Introduction to Matplotlib Library Tutorial

Python | Decay , Bayes Update ,Double Pendulum problem and Oscilloscope in...

4 comments

Raghav Sihna April 30, 2021 - 4:01 am

I just couldn’t go away your website before suggesting that I really
enjoyed the standard information an individual provide in your guests?
Is going to be again regularly to check out new posts

anupmaurya April 30, 2021 - 9:02 am

Subscribe to our Newsletter!

instagram takipçi satın al May 1, 2021 - 11:08 pm

Just want to say your article is as astonishing. The clearness in your post is just spectacular and i can assume you
are an expert on this subject. Well with your permission let me to grab your RSS feed to keep
up to date with forthcoming post. Thanks a million and please carry on the gratifying work.

John Krish May 6, 2021 - 10:51 am

Hi there, just wanted to say, I liked this article.
It was inspiring. Keep on posting!

Comments are closed.

PYTHON Tutorial

  • Online Python Compiler
  • Getting Started with Python
  • String in Python
  • Python Data Types
  • Python Operators
  • Python Keywords and Identifiers
  • Python Input, Output, and Import
  • Python if else
  • Python List
  • Python Dictionary
  • Python Libraries
  • Matplotib Tutorial
    • Python | Introduction to Matplotlib Library Tutorial
    • Python | Pyplot in Matplotlib Tutorial
    • Python | Ellipse, Pie Charts, Tables and Scatter Plot in Matplotlib
    • Python : PathPatch ,3D plotting & StreamPlot in Mathplotlib
    • Python: Plots, Images, Contour and Pseudocolor in Matplotlib

Keep in touch

Facebook Twitter Instagram Pinterest

Recent Posts

  • Types of JDBC drivers

    December 28, 2022
  • C++ Program to implements Constructor Overloading

    December 27, 2022
  • C++ Program to implements Constructor

    December 27, 2022
  • C++ Program to calculate the area using classes

    December 26, 2022

EDUCATIONAL

  • Difference between Google Cloud Platform, AWS and Azure

  • Google Apps You Should Be Using in 2022

  • Top Sites From Where You Can Learn

  • PyScript: Python in the Browser

  • Best Fake Email Generators (Free Temporary Email Address)

  • How to Find Out Who Owns a Domain Name

  • Mobile phone brands by country of origin

  • How to start a new YouTube Channel in 2022

  • Best way to use google search you won’t believe exist

  • 10 mostly asked questions related to WhatsApp

CHEATSHEET

  • Git and Github 2022 Cheat Sheet

  • ReactJs Cheatsheet

  • Linux Commands Cheat Sheet

  • C Programming language Cheatsheet

  • Scala Cheatsheet

  • MySQL Cheatsheet

  • Javascript Cheatsheet

PROJECTS

  • Print emojis using python without any module

  • Country Date and Time using Python

  • Covid-19 Tracker Application Using Python

  • Python | GUI Calendar using Tkinter

  • Python: Shutdown Computer with Voice

  • Python GUI Calculator using Tkinter

  • Convert an Image to ASCII art using Python

  • Python YouTube Downloader with Pytube

  • Tic-Tac-Toe using Python

  • Draw Indian Flag using Python

  • Drawing Pikachu with the Python turtle library

  • Word Dictionary using Tkinter

TECH NEWS

  • 5+ Best Humanoid Robots In The World

  • Reliance Jio launches streaming platform JioGamesWatch

  • Microsoft Teams down for thousands of users

  • Carbon: Google programming language as a C++ successor

JOBS AND INTERNSHIPS

  • Accenture Off Campus Hiring Drive | Associate Job | Program Project Management | 2019-2022 Batch| Apply Now

    September 1, 2022

@2019-21 - All Right Reserved. Designed and Developed by Techarge

TECHARGE
  • HOME
  • BLOGS
  • TUTORIALS
    • ALL TUTORIALS
    • PROGRAMMING TUTORIALS
      • JAVA TUTORIALS
      • C++ TUTORIAL
      • C PROGRAMMING TUTORIALS
      • PYTHON TUTORIAL
      • KNOWLEDGE MANAGEMENT TUTORIALS
      • DATA STRUCTURE AND ALGORITHM TUTORIALS
      • PROGRAMMING EXAMPLES
        • CPP EXAMPLES
        • JAVA EXAMPLES
        • C++ GRAPHICS PROGRAM
    • PROJECTS
      • PYTHON PROJECTS
      • SWIFT PROJECT
    • PPROGRAMMING QUIZ
    • DBMS TUTORIALS
    • COMPUTER NETWORK TUTORIALS
    • COMPUTER NETWORK SECURITY TUTORIALS
    • E COMMERCE TUTORIALS 
    • AWS TUTORIAL
    • INTERNET OF THINGS
    • CHEATSHEET
  • MORE
    • JOBS AND INTERNSHIPS
    • INTERVIEW PREPARATION
    • TECH BOOK
    • TECH NEWS
    • INSTAGRAM GALLERY
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • WEB STORIES
    • CONTACT US
  • WRITE +
  • ABOUT US