2 months, 4 weeks

Matplotlib In Python




Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays. Matplotlib is written in Python and makes use of NumPy, the numerical mathematics extension of Python. It provides an object-oriented API that helps in embedding plots in applications using Python GUI toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and IPython shells, Jupyter notebook and web application servers also. Matplotlib has a procedural interface named the Pylab, which is designed to resemble MATLAB, a proprietary programming language developed by MathWorks. Matplotlib along with NumPy can be considered as the open source equivalent of MATLAB. Matplotlib was originally written by John D. Hunter in 2003. The current stable version is 2.2.0 released in January 2018.

Ideally, the system package manager or pip should be used to install matplotlib, either by installing the python-matplotlib package or by running

pip install matplotlib                                                                          

Debian/Ubuntu:                sudo apt-get install python-matplotlib

Fedora/Red Hat:               sudo yum install python-matplotlib

 

from matplotlib import pyplot as plt

import numpy as np

import math

#needed for definition of pi

x=np.arange(0, math.pi*2, 0.05)

y=np.sin(x) plt.plot(x,y)

plt.xlabel("angle")

plt.ylabel("sine")

plt.title('sine wave')

plt.show()

# Customize the plot

ax.grid(1, ls='--', color='#777777', alpha=0.5, lw=1)

ax.tick_params(labelsize=12, length=0)

ax.set_axis_bgcolor('w')

# add a legend

leg = plt.legend( ['text'], loc=1 )

fr = leg.get_frame()

fr.set_facecolor('w')

fr.set_alpha(.7)

plt.draw()

import numpy as np

from matplotlib.pyplot

import imshow, show, colorbar

image = np.random.rand(4,4)

imshow(image)

colorbar()

show()

import matplotlib.pyplot as plt

plt.plot([1,2,3])

plt.subplot(211)

plt.plot(range(12))

plt.subplot(212, facecolor='y')

# creates 2nd subplot with a yellow background

plt.plot(range(12))

import matplotlib.pyplot as plt

a1= plt.subplot2grid((3,3),(0,0),colspan=2)

a2=plt.subplot2grid((3,3),(0,2), rowspan=3)

a3=plt.subplot2grid((3,3),(1,0),rowspan=2, colspan=2)

import numpy as np

x=np.arange(1,10)

a2.plot(x, x*x)

a2.set_title('square')

a1.plot(x, np.exp(x))

a1.set_title('exp')

a3.plot(x, np.log(x))

a3.set_title('log')

plt.tight_layout()

plt.show()

import matplotlib.pyplot as plt

fig=plt.figure()

ax=fig.add_axes([0,0,1,1])

ax.spines['bottom'].set_color('blue')

ax.spines['left'].set_color('red')

ax.spines['left'].set_linewidth(2)

ax.spines['right'].set_color(None)

ax.spines['top'].set_color(None)

ax.plot([1,2,3,4,5])

plt.show()

 

import matplotlib.pyplot as plt

import numpy as np

fig=plt.figure()

a1=fig.add_axes([0,0,1,1])

x=np.arange(1,11)

a1.plot(x,np.exp(x))

a1.set_ylabel('exp')

a2=a1.twinx()

a2.plot(x, np.log(x),'ro-')

a2.set_ylabel('log')

fig.legend(labels=('exp','log'),loc='upper left')

plt.show()

import numpy as np

import matplotlib.pyplot as plt

xlist = np.linspace(-3.0, 3.0, 100)

ylist = np.linspace(-3.0, 3.0, 100)

X, Y = np.meshgrid(xlist, ylist)

Z = np.sqrt(X**2 + Y**2)

fig,ax=plt.subplots(1,1)

cp = ax.contourf(X, Y, Z)

fig.colorbar(cp)

# Add a colorbar to a plot

ax.set_title('Filled Contours Plot')

ax.set_ylabel('y (cm)')

plt.show()

Matplotlib GitHub               

Three-dimensional plots                                                                             

X = np.arange(0, 6, 0.25)                                                       
Y = np.arange(0, 6, 0.25)                                                      
X, Y = np.meshgrid(X, Y)                                                     
Z1 = np.empty_like(X)                                                         
Z2 = np.empty_like(X)                                                        
C1 = np.empty_like(X, dtype=object)                                  
C2 = np.empty_like(X, dtype=object)                                   
for i in range(len(X)):                                                          
 for j in range(len(X[0])):                                                    
 z1 = 0.5*(erf((X[i,j]+Y[i,j]-4.5)*0.5)+1)                                   
 z2 = 0.5*(erf((-X[i,j]-Y[i,j]+4.5)*0.5)+1)                                   
 Z1[i,j] = z1                                                                               
 Z2[i,j] = z2                                                                                 
 # If you want to grab a colour from a matplotlib cmap function,             
 # you need to give it a number between 0 and 1. z1 and z2 are            
 # already in this range, so it just works as is.                                        
 C1[i,j] = plt.get_cmap("Oranges")(z1)                                                    
 C2[i,j] = plt.get_cmap("Blues")(z2)                                                        
# Create a transparent bridge region                                                      
X_bridge = np.vstack([X[-1,:],X[-1,:]])                                                         
Y_bridge = np.vstack([Y[-1,:],Y[-1,:]])                                                           
Z_bridge = np.vstack([Z1[-1,:],Z2[-1,:]])                                                     
color_bridge = np.empty_like(Z_bridge, dtype=object)                                                 
color_bridge.fill((1,1,1,0)) # RGBA colour, onlt the last component matters - 
# Join the two surfaces flipping one of them (using also the bridge)                              
X_full = np.vstack([X, X_bridge, np.flipud(X)])                                                   
Y_full = np.vstack([Y, Y_bridge, np.flipud(Y)])                                                     
Z_full = np.vstack([Z1, Z_bridge, np.flipud(Z2)])                                              
color_full = np.vstack([C1, color_bridge, np.flipud(C2)])                                
surf_full = ax.plot_surface(X_full, Y_full, Z_full, rstride=1, cstride=1,  facecolors=color_full, linewidth=0, antialiased=False)
plt.show()                                                                              

 

The image module in Matplotlib package provides functionalities required for loading, rescaling and displaying image.
Loading image data is supported by the Pillow library. Natively, Matplotlib only supports PNG images. The commands shown below fall back on Pillow if the native read fails. The image used in this example is a PNG file, but keep that Pillow requirement in mind for your own data. The imread() function is used to read image data in an ndarray object of float32 dtype.


import matplotlib.pyplot as plt                                   
import matplotlib.image as mpimg                             
import numpy as np                                                    
img=mpimg.imread('mtplogo.png')                              

 


Responses(0)