0% found this document useful (0 votes)
2 views

Matplotlib_Cheat_Sheet

The document is a comprehensive cheat sheet for using Matplotlib, a Python 2D plotting library, covering various plotting routines for 1D and 2D data, including customization options for colors, markers, and annotations. It outlines the basic workflow for creating plots, including data preparation, plotting, customization, saving, and displaying figures. Additionally, it provides examples of different plot types, such as line plots, scatter plots, bar charts, and histograms.

Uploaded by

shailesh993151
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Matplotlib_Cheat_Sheet

The document is a comprehensive cheat sheet for using Matplotlib, a Python 2D plotting library, covering various plotting routines for 1D and 2D data, including customization options for colors, markers, and annotations. It outlines the basic workflow for creating plots, including data preparation, plotting, customization, saving, and displaying figures. Additionally, it provides examples of different plot types, such as line plots, scatter plots, bar charts, and histograms.

Uploaded by

shailesh993151
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

> Plotting Routines > Plotting Cutomize Plot

Python For Data Science


1D Data
>>> fig, ax = plt.subplots()

Colors, Color Bars & Color Maps


>>> plt.plot(x, x, x, x**2, x, x**3)

Matplotlib Cheat Sheet >>>


>>>
>>>
>>>
lines = ax.plot(x,y) #Draw points with lines or markers connecting them

ax.scatter(x,y) #Draw unconnected points, scaled or colored

axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)

axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)

>>>
>>>
>>>
>>>
ax.plot(x, y, alpha = 0.4)

ax.plot(x, y, c='k')

fig.colorbar(im, orientation='horizontal')

im = ax.imshow(img,

>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes


cmap='seismic')
Learn Matplotlib online at www.DataCamp.com >>> axes[0,1].axvline(0.65) #Draw a vertical line across axes

>>> ax.fill(x,y,color='blue') #Draw filled polygons

>>> ax.fill_between(x,y,color='yellow') #Fill between y-values and 0 Markers


2D Data >>> fig, ax = plt.subplots()

Matplotlib >>> fig, ax = plt.subplots()

>>> ax.scatter(x,y,marker=".")

>>> ax.plot(x,y,marker="o")

>>> im = ax.imshow(img, #Colormapped or RGB arrays

Matplotlib is a Python 2D plotting library which produces


cmap='gist_earth',
Linestyles
interpolation='nearest',

publication-quality figures in a variety of hardcopy formats and


vmin=-2,

interactive environments across platforms. vmax=2)


>>> plt.plot(x,y,linewidth=4.0)

>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array


>>> plt.plot(x,y,ls='solid')

Also see lists & NumPy


>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> plt.plot(x,y,ls='--')

>>> CS = plt.contour(Y,X,U) #Plot contours


>>> plt.plot(x,y,'--',x**2,y**2,'-.')

> Prepare The Data >>> axes2[2].contourf(data1) #Plot filled contours

>>> axes2[2]= ax.clabel(CS) #Label a contour plot


>>> plt.setp(lines,color='r',linewidth=4.0)

Text & Annotations


1D Data Vector Fields
>>> ax.text(1,

>>> import numpy as np


>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
-2.1,

>>> x = np.linspace(0, 10, 100)


>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
'Example Graph',

>>> y = np.cos(x)
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows style='italic')

>>> z = np.sin(x) >>> ax.annotate("Sine",

xy=(8, 0),

Data Distributions xycoords='data',

2D Data or Images xytext=(10.5, 0),

textcoords='data',

>>> ax1.hist(y) #Plot a histogram


arrowprops=dict(arrowstyle="->",

>>> data = 2 * np.random.random((10, 10))


>>> ax3.boxplot(y) #Make a box and whisker plot
connectionstyle="arc3"),)
>>> data2 = 3 * np.random.random((10, 10))
>>> ax3.violinplot(z) #Make a violin plot
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]

>>> U = -1 - X**2 + Y
Mathtext
>>> V = 1 + X - Y**2

>>>
>>>
from matplotlib.cbook import get_sample_data

img = np.load(get_sample_data('axes_grid/bivariate_normal.npy')) > Plot Anatomy & Workflow >>> plt.title(r'$sigma_i=15$', fontsize=20)

Plot Anatomy Limits, Legends and Layouts


> Create Plot Limits & Autoscaling
Axes/Subplot
>>> import matplotlib.pyplot as plt >>> ax.margins(x=0.0,y=0.1) #Add padding to a plot

>>> ax.axis('equal') #Set the aspect ratio of the plot to 1

>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5]) #Set limits for x-and y-axis

Figure Y-axis Figure >>> ax.set_xlim(0,10.5) #Set limits for x-axis

Legends
>>> fig = plt.figure()

>>> ax.set(title='An Example Axes', #Set a title and x-and y-axis labels

>>> fig2 = plt.figure(figsize=plt.figaspect(2.0)) X- axis


ylabel='Y-Axis',

xlabel='X-Axis')

Axes Workflow >>> ax.legend(loc='best') #No overlapping plot elements

The basic steps to creating plots with matplotlib are: Ticks


All plotting is done with respect to an Axes. In most cases, a subplot will fit your needs.
1 Prepare Data 2 Create Plot 3 Plot 4 Customized Plot 5 Save Plot 6 Show Plot >>> ax.xaxis.set(ticks=range(1,5), #Manually set x-ticks

A subplot is an axes on a grid system. ticklabels=[3,100,-12,"foo"])

>>> import matplotlib.pyplot as plt


>>> ax.tick_params(axis='y', #Make y-ticks longer and go in and out

>>> fig.add_axes()
>>> x = [1,2,3,4] #Step 1
direction='inout',

>>> ax1 = fig.add_subplot(221) #row-col-num


>>> y = [10,20,25,30]
length=10)
>>> ax3 = fig.add_subplot(212)
>>> fig = plt.figure() #Step 2

>>> fig3, axes = plt.subplots(nrows=2,ncols=2)


>>> ax = fig.add_subplot(111) #Step 3
Subplot Spacing
>>> fig4, axes2 = plt.subplots(ncols=3) >>> ax.plot(x, y, color='lightblue', linewidth=3) #Step 3, 4

>>> ax.scatter([2,4,6],
>>> fig3.subplots_adjust(wspace=0.5, #Adjust the spacing between subplots

[5,15,25],
hspace=0.3,

left=0.125,

> Save Plot


color='darkgreen',

marker='^')
right=0.9,

>>> ax.set_xlim(1, 6.5)


top=0.9,

>>> plt.savefig('foo.png') #Step 5


bottom=0.1)

>>> plt.savefig('foo.png') #Save figures


>>> plt.show() #Step 6 >>> fig.tight_layout() #Fit subplot(s) in to the figure area
>>> plt.savefig('foo.png', transparent=True) #Save transparent figures
Axis Spines

>>> ax1.spines['top'].set_visible(False) #Make the top axis line for a plot invisible

> Show Plot > Close and Clear >>> ax1.spines['bottom'].set_position(('outward',10)) #Move the bottom axis line outward

>>> plt.cla() #Clear an axis

>>> plt.show()
>>> plt.clf() #Clear the entire figure

>>> plt.close() #Close a window


Learn Data Skills Online at www.DataCamp.com

You might also like