Matplotlib Merged Merged
Matplotlib Merged Merged
Data visualization
Human minds are more adaptive for the visual representation of data rather than
textual data. We can easily understand things when they are visualized.
Can be achieved using visual elements like figures, charts, graphs, maps.
Matplotlib
Install Matplotlib
The python package manager pip is also used to install matplotlib. Open
the command prompt window, and type the following command:
Figure: It is a whole figure which may hold one or more axes (plots). We
can think of a Figure as a canvas that holds plots.
Axes: A Figure can contain several Axes. It consists of two or three (in
the case of 3D) Axis objects. Each Axes is comprised of a title, an x-label,
and a y-label.
Axis: Axises are the number of line like objects and responsible for
generating the graph limits.
Artist: An artist is the all which we see on the graph like Text objects,
Line2D objects, and collection objects. Most Artists are tied to Axes.
Verify the Installation
1. import matplotlib
2. matplotlib.__version__
plt.plot(x,y)
plt.show()
Matplotlib is a popular data visualization library in Python that provides a wide range
of tools for creating high-quality static and interactive visualizations. It is an open-
source library that is widely used in scientific computing, data analysis, and machine
learning. Some of the advantages and features of Matplotlib are:
1. Ease of use: Matplotlib provides a simple and intuitive interface for creating
visualizations. It allows users to create complex plots with just a few lines of code.
4. Wide range of plot types: Matplotlib supports a wide range of plot types,
including line plots, scatter plots, bar plots, histograms, and more.
5. Integration with other libraries: Matplotlib integrates well with other Python
libraries such as NumPy, Pandas, and SciPy.
8. Large community: Matplotlib has a large community of users and developers who
contribute to its development and provide support to users.
10. Free and open-source: Matplotlib is free to use and distribute under the BSD
license.
1. Ease of use: Python Matplotlib is easy to use and has a simple syntax that allows
users to create complex visualizations with just a few lines of code. It provides a wide
range of customization options, including colors, fonts, labels, and annotations.
2. Flexibility: Python Matplotlib is highly flexible and can be used to create a wide
range of visualizations, including line charts, scatter plots, bar charts, histograms,
heatmaps, and more. It also supports multiple data formats, including CSV files, Excel
spreadsheets, and SQL databases.
1. Line Plot: A line plot is a basic plot that displays data points connected by straight
lines. It is useful for visualizing trends and patterns in data over time.
2. Scatter Plot: A scatter plot displays data points as individual dots on a graph. It is
useful for visualizing the relationship between two variables.
3. Bar Plot: A bar plot displays data as rectangular bars with heights or lengths
proportional to the values they represent. It is useful for comparing different
categories of data.
5. Pie Chart: A pie chart displays data as slices of a circle, with each slice representing
a proportion of the whole. It is useful for showing how different categories
contribute to a total.
6. Heatmap: A heatmap displays data as a grid of colored squares, with each square
representing a value in the dataset. It is useful for visualizing patterns in large
datasets.
7. Contour Plot: A contour plot displays data as contours or lines of constant value
on a 2D surface. It is useful for visualizing functions of two variables.
8. 3D Plot: Matplotlib also provides several types of 3D plots, including surface plots,
wireframe plots, and scatter plots in 3D space.
Overall, Matplotlib provides a wide range of plotting options that can be customized
to suit specific needs and preferences.
bar-plot
1 BAR plot
[1]: import matplotlib.pyplot as plt
import numpy as np
[11]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
plt.bar(x,y,color='r')
plt.show()
1
[14]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
plt.xlabel("language",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("DATA vs Language",fontsize=15)
c=['#A2B3C3','#F2A323','#D2D3C3','#A2B3E3','#F2B3E3']
plt.bar(x,y,width=0.4,color=c,align="edge")
plt.show()
[17]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
plt.xlabel("language",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("DATA vs Language",fontsize=15)
2
c=['#A2B3C3','#F2A323','#D2D3C3','#A2B3E3','#F2B3E3']
plt.bar(x,y,width=0.4,color=c,edgecolor='black',
linewidth=2,linestyle='--',alpha=0.5)
plt.show()
[20]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
plt.xlabel("language",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("DATA vs Language",fontsize=15)
c=['#A2B3C3','#F2A323','#D2D3C3','#A2B3E3','#F2B3E3']
plt.bar(x,y,width=0.4,color=c,edgecolor='black',
label='Popularity')
3
plt.legend()
plt.show()
[21]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
z=[34,25,23,81,23]
plt.xlabel("language",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("DATA vs Language",fontsize=15)
c=['#A2B3C3','#F2A323','#D2D3C3','#A2B3E3','#F2B3E3']
plt.bar(x,y,width=0.4,color=c,edgecolor='black',
label='Popularity')
c1=['#22F313','#02A323','#ABD3C3','#11B3E3','#06B3E3']
plt.bar(x,z,width=0.4,color=c1,edgecolor='black',
4
label='Popularity1')
plt.legend()
plt.show()
[7]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
z=[34,25,23,81,23]
plt.xlabel("language",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("DATA vs Language",fontsize=15)
width=0.3
p=np.arange(len(x))
p1=[j+width for j in p]
c=['#A2B3C3','#F2A323','#D2D3C3','#A2B3E3','#F2B3E3']
c1=['#22F313','#A2F323','#ABD3C3','#11B3E3','#06B3E3']
5
plt.bar(p,y,width,color=c,edgecolor='black',
label='Popularity')
plt.bar(p1,z,width,color=c1,edgecolor='black',
label='Popularity1')
plt.legend()
plt.show()
[8]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
z=[34,25,23,81,23]
plt.xlabel("language",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("DATA vs Language",fontsize=15)
width=0.3
p=np.arange(len(x))
p1=[j+width for j in p]
6
c=['#A2B3C3','#F2A323','#D2D3C3','#A2B3E3','#F2B3E3']
c1=['#22F313','#A2F323','#ABD3C3','#11B3E3','#06B3E3']
plt.bar(p,y,width,color=c,edgecolor='black',
label='Popularity')
plt.bar(p1,z,width,color=c1,edgecolor='black',
label='Popularity1')
plt.xticks(p+width/2,x,rotation=20)
plt.legend()
plt.show()
[9]: x=["Python",'PHP','JAVA','UX/UI','CSS3']
y=[90,58,84,92,78]
z=[34,25,23,81,23]
7
plt.xlabel("language",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("DATA vs Language",fontsize=15)
c=['#A2B3C3','#F2A323','#D2D3C3','#A2B3E3','#F2B3E3']
c1=['#22F313','#A2F323','#ABD3C3','#11B3E3','#06B3E3']
plt.barh(x,y,color=c,edgecolor='black',
label='Popularity')
plt.barh(x,z,color=c1,edgecolor='black',
label='Popularity1')
plt.legend()
plt.show()
[ ]:
8
box-plot
1 Box Plot
[1]: import matplotlib.pyplot as plt
[2]: ['magma',
'inferno',
'plasma',
'viridis',
'cividis',
'twilight',
'twilight_shifted',
'turbo',
'Blues',
'BrBG',
'BuGn',
'BuPu',
'CMRmap',
'GnBu',
'Greens',
'Greys',
'OrRd',
'Oranges',
'PRGn',
'PiYG',
'PuBu',
'PuBuGn',
'PuOr',
'PuRd',
'Purples',
'RdBu',
'RdGy',
'RdPu',
'RdYlBu',
'RdYlGn',
'Reds',
1
'Spectral',
'Wistia',
'YlGn',
'YlGnBu',
'YlOrBr',
'YlOrRd',
'afmhot',
'autumn',
'binary',
'bone',
'brg',
'bwr',
'cool',
'coolwarm',
'copper',
'cubehelix',
'flag',
'gist_earth',
'gist_gray',
'gist_heat',
'gist_ncar',
'gist_rainbow',
'gist_stern',
'gist_yarg',
'gnuplot',
'gnuplot2',
'gray',
'hot',
'hsv',
'jet',
'nipy_spectral',
'ocean',
'pink',
'prism',
'rainbow',
'seismic',
'spring',
'summer',
'terrain',
'winter',
'Accent',
'Dark2',
'Paired',
'Pastel1',
'Pastel2',
'Set1',
'Set2',
2
'Set3',
'tab10',
'tab20',
'tab20b',
'tab20c',
'magma_r',
'inferno_r',
'plasma_r',
'viridis_r',
'cividis_r',
'twilight_r',
'twilight_shifted_r',
'turbo_r',
'Blues_r',
'BrBG_r',
'BuGn_r',
'BuPu_r',
'CMRmap_r',
'GnBu_r',
'Greens_r',
'Greys_r',
'OrRd_r',
'Oranges_r',
'PRGn_r',
'PiYG_r',
'PuBu_r',
'PuBuGn_r',
'PuOr_r',
'PuRd_r',
'Purples_r',
'RdBu_r',
'RdGy_r',
'RdPu_r',
'RdYlBu_r',
'RdYlGn_r',
'Reds_r',
'Spectral_r',
'Wistia_r',
'YlGn_r',
'YlGnBu_r',
'YlOrBr_r',
'YlOrRd_r',
'afmhot_r',
'autumn_r',
'binary_r',
'bone_r',
'brg_r',
3
'bwr_r',
'cool_r',
'coolwarm_r',
'copper_r',
'cubehelix_r',
'flag_r',
'gist_earth_r',
'gist_gray_r',
'gist_heat_r',
'gist_ncar_r',
'gist_rainbow_r',
'gist_stern_r',
'gist_yarg_r',
'gnuplot_r',
'gnuplot2_r',
'gray_r',
'hot_r',
'hsv_r',
'jet_r',
'nipy_spectral_r',
'ocean_r',
'pink_r',
'prism_r',
'rainbow_r',
'seismic_r',
'spring_r',
'summer_r',
'terrain_r',
'winter_r',
'Accent_r',
'Dark2_r',
'Paired_r',
'Pastel1_r',
'Pastel2_r',
'Set1_r',
'Set2_r',
'Set3_r',
'tab10_r',
'tab20_r',
'tab20b_r',
'tab20c_r']
[3]: x=[10,20,30,40,50,60,70]
plt.subplot(2,2,1)
plt.boxplot(x,labels=['Python'])
4
plt.subplot(2,2,2)
plt.boxplot(x,notch=True)
plt.subplot(2,2,3)
plt.boxplot(x,vert=False)
plt.subplot(2,2,4)
plt.boxplot(x,widths=0.4)
plt.show()
[11]: x=[10,20,30,40,50,60,70]
plt.subplot(2,2,1)
plt.boxplot(x,labels=['Python'])
plt.subplot(2,2,2)
plt.boxplot(x,patch_artist=True)
plt.subplot(2,2,3)
5
plt.boxplot(x,showmeans=True)
x2=[10,20,30,40,50,60,70,120]
plt.subplot(2,2,4)
plt.boxplot(x2)
plt.show()
[12]: x=[10,20,30,40,50,60,70,120]
plt.subplot(2,2,1)
plt.boxplot(x,sym=' ') # hide outlier
x1=[10,20,30,40,50,60,70,120,130]
plt.subplot(2,2,2)
plt.boxplot(x1)
plt.subplot(2,2,3)
6
plt.boxplot(x,whis=2)
plt.subplot(2,2,4)
plt.boxplot(x,sym='rH')
plt.show()
[6]: x=[10,20,30,40,50,60,70,120]
plt.boxplot(x,labels=['Python'],showmeans=True,sym='mD',
boxprops=dict(color='r'),capprops=dict(color='m'),
whiskerprops=dict(color='g'),
flierprops=dict(markeredgecolor='y'))
plt.show()
7
[7]: x=[10,20,30,40,50,60,70]
x1=[10,20,30,50,20,50,90]
y=[x,x1]
plt.boxplot(y,labels=['Python','CSS3'],showmeans=True,sym='mD',
boxprops=dict(color='r'),capprops=dict(color='m'),
whiskerprops=dict(color='g'))
plt.show()
8
[ ]:
9
fill-between
[6]: x=[1,2,3,4,5]
y=[1,2,3,4,5]
plt.plot(x,y,color='r')
plt.fill_between(x,y,color='y')
plt.title('Step Plot')
plt.xlabel('X - Axis')
plt.ylabel('Y - Axis')
plt.show()
1
[10]: x=[1,2,3,4,5]
y=[1,2,3,4,5]
plt.plot(x,y,color='r')
plt.fill_between(x=[2,4],y1=2,y2=4,color='m')
plt.title('Step Plot')
plt.xlabel('X - Axis')
plt.ylabel('Y - Axis')
plt.show()
2
[15]: x=np.array([1,2,3,4,5])
y=np.array([1,2,3,4,5])
plt.plot(x,y,color='r')
plt.title('Step Plot')
plt.xlabel('X - Axis')
plt.ylabel('Y - Axis')
plt.show()
3
[ ]:
4
histogram-plot
1 Histogram_plot
[1]: import matplotlib.pyplot as plt
import numpy as np
import random
[4]: x=np.random.randint(10,60,(50))
print(x)
[26 41 20 48 57 24 16 53 14 13 27 28 39 24 23 58 44 47 52 14 46 48 45 27
51 56 25 58 23 16 29 57 28 57 38 32 59 16 51 17 20 28 51 27 54 39 51 28
51 22]
[2]: no=[26,41,20,48,57,24,16,53,14,13,27,28,39,24,23,58,44,47,52,14,46,48,45,27,
51,56,25,58,23,16,29,57,28,57,38,32,59,16,51,17,20,28,51,27,54,39,51,28,
51,22]
plt.hist(no,color='#AF2345',edgecolor='black')
plt.xlabel("Python",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("Scatter Plot",fontsize=15)
plt.show()
1
[13]: no=[26,41,20,48,57,24,16,53,14,13,27,28,39,24,23,58,44,47,52,14,46,48,45,27,
51,56,25,58,23,16,29,57,28,57,38,32,59,16,51,17,20,28,51,27,54,39,51,28,
51,22]
bin=[10,20,30,40,50,60]
plt.hist(no,color='#AF2345',edgecolor='black',bins=bin)
plt.xlabel("Python",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("Scatter Plot",fontsize=15)
plt.show()
2
[16]: no=[26,41,20,48,57,24,16,53,14,13,27,28,39,24,23,58,44,47,52,14,46,48,45,27,
51,56,25,58,23,16,29,57,28,57,38,32,59,16,51,17,20,28,51,27,54,39,51,28,
51,22]
bin=[10,20,30,40,50,60]
plt.hist(no,"auto",(0,100),edgecolor='black')
plt.xlabel("Python",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("Scatter Plot",fontsize=15)
plt.show()
3
[5]: no=[26,41,20,48,57,24,16,53,14,13,27,28,39,24,23,58,44,47,52,14,46,48,45,27,
51,56,25,58,23,16,29,57,28,57,38,32,59,16,51,17,20,28,51,27,54,39,51,28,
51,22]
plt.hist(no,color='#F2FD45',edgecolor='black',
cumulative=-1,bottom=10)
plt.xlabel("Python",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("Scatter Plot",fontsize=15)
plt.show()
4
[35]: no=[26,41,20,48,57,24,16,53,14,13,27,28,39,24,23,58,44,47,52,14,46,48,45,27,
51,56,25,58,23,16,29,57,28,57,38,32,59,16,51,17,20,28,51,27,54,39,51,28,
51,22]
plt.hist(no,color='#AF2345',edgecolor='black',
align='left',histtype='step')
plt.xlabel("Python",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("Scatter Plot",fontsize=15)
plt.grid()
plt.show()
5
[27]: no=[26,41,20,48,57,24,16,53,14,13,27,28,39,24,23,58,44,47,52,14,46,48,45,27,
51,56,25,58,23,16,29,57,28,57,38,32,59,16,51,17,20,28,51,27,54,39,51,28,
51,22]
plt.hist(no,color='#AF2345',edgecolor='black',orientation='horizontal',rwidth=0.
↪8)
plt.xlabel("Python",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("Scatter Plot",fontsize=15)
plt.show()
6
[34]: no=[26,41,20,48,57,24,16,53,14,13,27,28,39,24,23,58,44,47,52,14,46,48,45,27,
51,56,25,58,23,16,29,57,28,57,38,32,59,16,51,17,20,28,51,27,54,39,51,28,
51,22]
plt.hist(no,color='#AF23DF',
edgecolor='black',
rwidth=0.8,log=True,label='Python')
plt.xlabel("Python",fontsize=15)
plt.ylabel("NO.",fontsize=15)
plt.title("Scatter Plot",fontsize=15)
plt.axvline(35,color='g',label='line')
plt.legend()
plt.show()
7
[ ]:
8
img-read
1 Imshow
[1]: import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img.shape
[4]: plt.imshow(img)
plt.show()
[5]: plt.figure(figsize=(15,5))
plt.axis('off')
plt.imshow(img,cmap='RdGy')
1
plt.colorbar()
plt.show()
[11]: sc=img[:,:,1]
plt.figure(figsize=(15,5))
plt.axis('off')
plt.imshow(sc,cmap='summer')
plt.colorbar()
plt.savefig('goku.jpg')
plt.show()
2
[ ]:
[ ]:
def plot_all_cmaps():
N_ROWS, N_COLS = 8, 7 # 13, 13 <-- for all in one figure
HEIGHT, WIDTH = 7, 14
cmap_ids = plt.colormaps()
n_cmaps = len(cmap_ids)
index = 0
while index < n_cmaps:
fig, axes = plt.subplots(N_ROWS, N_COLS, figsize=(WIDTH, HEIGHT))
for row in range(N_ROWS):
for col in range(N_COLS):
ax = axes[row, col]
cmap_id = cmap_ids[index]
cmap = plt.get_cmap(cmap_id)
mpl.colorbar.ColorbarBase(ax, cmap=cmap,
orientation='horizontal')
ax.set_title(f"'{cmap_id}', {index}", fontsize=8)
ax.tick_params(left=False, right=False, labelleft=False,
labelbottom=False, bottom=False)
plot_all_cmaps()
3
4
[ ]:
5
pie-plot
1 Pie Plot
[1]: import matplotlib.pyplot as plt
[14]: x=[10,20,30,40]
y=['c','CSS3','Node JS','Python']
exp=[0.3,0.0,0.1,0.0]
plt.pie(x,labels=y,explode=exp)
plt.show()
1
[3]: x=[10,20,30,40]
y=['c','CSS3','Node JS','Python']
exp=[0.0,0.2,0.0,0.0]
color=['#B8B436','#EDE7D9','#ACC1F0','#DD403A']
plt.pie(x,labels=y,explode=exp,
colors=color, autopct="%0.2f%%",
shadow=True,radius=1.3,labeldistance=1.3)
plt.show()
[4]: x=[10,20,30,40]
y=['c','CSS3','Node JS','Python']
exp=[0.0,0.2,0.0,0.0]
color=['#B8B436','#FF77D9','#ACC1F0','#DD403A']
2
plt.pie(x,labels=y,explode=exp,
colors=color, autopct="%0.2f%%",
shadow=True,startangle=90,
textprops={"fontsize":12,"color":'white'})
plt.show()
[16]: x=[10,20,30,40]
y=['c','CSS3','Node JS','Python']
exp=[0.0,0.2,0.0,0.0]
color=['#B8B436','#FF77D9','#ACC1F0','#DD403A']
plt.pie(x,labels=y,explode=exp,
colors=color, autopct="%0.2f%%",
shadow=True,counterclock=False,
wedgeprops={'linewidth':5,'edgecolor':'y'},
center=(1,3),rotatelabels=True)
plt.title("Pie Plot")
plt.legend(loc=2)
plt.show()
3
[6]: plt.pie([1])
plt.show()
4
[7]: x=[10,20,30,40]
x1=[40,30,20,60]
y=['c','C++','JAVA','React jS']
plt.pie(x,labels=y,radius=1.5)
plt.pie(x1,radius=0.7)
plt.show()
5
[8]: x=[10,20,30,40]
x1=[40,30,20,60]
y=['c','C++','JAVA','React jS']
plt.pie(x,labels=y,radius=1.3)
plt.pie([1],colors='white',radius=0.7)
plt.show()
6
[9]: x=[10,20,30,40]
x1=[40,30,20,60]
y=['c','C++','JAVA','React jS']
plt.pie(x,labels=y,radius=1.3)
cr=plt.Circle(xy=(0,0),radius=1,facecolor='w')
plt.gca().add_artist(cr)
plt.show()
7
[ ]:
8
plot-plot
1
[5]: matplotlib.__version__
[5]: '3.5.2'
[38]: x=[1,2,3,4,5,6]
y=[12,43,64,12,65,23]
plt.plot(x,y,color='g',linewidth=2,linestyle=':',marker='H',markersize=15)
plt.show()
[ ]:
2
scatter-plot
1 Scatter plot
[1]: import matplotlib.pyplot as plt
[2]: day=[1,2,3,4,5,6]
y=[2,4,1,6,8,4]
plt.scatter(day,y,color='r',s=120)
plt.title("Scatter Plot",fontsize=15)
plt.xlabel("Day",fontsize=15)
plt.ylabel("No",fontsize=15)
plt.show()
1
[3]: day=[1,2,3,4,5,6]
y=[2,4,1,6,8,4]
c=['#F24236','#2E86AB','#CBE896','#6320EE','#A2B3E3','#F2B3E3']
sizes=[45,78,65,154,79,97]
plt.scatter(day,y,color=c,s=sizes,alpha=0.5)
plt.title("Scatter Plot",fontsize=15)
plt.xlabel("Day",fontsize=15)
plt.ylabel("No",fontsize=15)
plt.show()
2
[4]: day=[1,2,3,4,5,6]
y=[2,4,1,6,8,4]
c=['#F24236','#2E86AB','#CBE896','#6320EE','#A2B3E3','#F2B3E3']
sizes=[145,108,165,254,179,197]
plt.scatter(day,y,color=c,s=sizes,marker='D',edgecolors='black',linewidths=1)
plt.title("Scatter Plot",fontsize=15)
plt.xlabel("Day",fontsize=15)
plt.ylabel("No",fontsize=15)
plt.show()
3
[7]: plt.colormaps()
[7]: ['magma',
'inferno',
'plasma',
'viridis',
'cividis',
'twilight',
'twilight_shifted',
'turbo',
'Blues',
'BrBG',
'BuGn',
'BuPu',
'CMRmap',
'GnBu',
'Greens',
'Greys',
'OrRd',
4
'Oranges',
'PRGn',
'PiYG',
'PuBu',
'PuBuGn',
'PuOr',
'PuRd',
'Purples',
'RdBu',
'RdGy',
'RdPu',
'RdYlBu',
'RdYlGn',
'Reds',
'Spectral',
'Wistia',
'YlGn',
'YlGnBu',
'YlOrBr',
'YlOrRd',
'afmhot',
'autumn',
'binary',
'bone',
'brg',
'bwr',
'cool',
'coolwarm',
'copper',
'cubehelix',
'flag',
'gist_earth',
'gist_gray',
'gist_heat',
'gist_ncar',
'gist_rainbow',
'gist_stern',
'gist_yarg',
'gnuplot',
'gnuplot2',
'gray',
'hot',
'hsv',
'jet',
'nipy_spectral',
'ocean',
'pink',
5
'prism',
'rainbow',
'seismic',
'spring',
'summer',
'terrain',
'winter',
'Accent',
'Dark2',
'Paired',
'Pastel1',
'Pastel2',
'Set1',
'Set2',
'Set3',
'tab10',
'tab20',
'tab20b',
'tab20c',
'magma_r',
'inferno_r',
'plasma_r',
'viridis_r',
'cividis_r',
'twilight_r',
'twilight_shifted_r',
'turbo_r',
'Blues_r',
'BrBG_r',
'BuGn_r',
'BuPu_r',
'CMRmap_r',
'GnBu_r',
'Greens_r',
'Greys_r',
'OrRd_r',
'Oranges_r',
'PRGn_r',
'PiYG_r',
'PuBu_r',
'PuBuGn_r',
'PuOr_r',
'PuRd_r',
'Purples_r',
'RdBu_r',
'RdGy_r',
'RdPu_r',
6
'RdYlBu_r',
'RdYlGn_r',
'Reds_r',
'Spectral_r',
'Wistia_r',
'YlGn_r',
'YlGnBu_r',
'YlOrBr_r',
'YlOrRd_r',
'afmhot_r',
'autumn_r',
'binary_r',
'bone_r',
'brg_r',
'bwr_r',
'cool_r',
'coolwarm_r',
'copper_r',
'cubehelix_r',
'flag_r',
'gist_earth_r',
'gist_gray_r',
'gist_heat_r',
'gist_ncar_r',
'gist_rainbow_r',
'gist_stern_r',
'gist_yarg_r',
'gnuplot_r',
'gnuplot2_r',
'gray_r',
'hot_r',
'hsv_r',
'jet_r',
'nipy_spectral_r',
'ocean_r',
'pink_r',
'prism_r',
'rainbow_r',
'seismic_r',
'spring_r',
'summer_r',
'terrain_r',
'winter_r',
'Accent_r',
'Dark2_r',
'Paired_r',
'Pastel1_r',
7
'Pastel2_r',
'Set1_r',
'Set2_r',
'Set3_r',
'tab10_r',
'tab20_r',
'tab20b_r',
'tab20c_r']
[13]: day=[1,2,3,4,5,6]
y=[2,4,1,6,8,4]
c=[13,54,32,78,95,36]
sizes=[145,108,165,254,179,197]
plt.scatter(day,y,c=c,s=sizes,
cmap='spring',
marker='^',edgecolors='black',linewidths=1)
plt.title("Scatter Plot",fontsize=15)
plt.xlabel("Day",fontsize=15)
plt.ylabel("No",fontsize=15)
t=plt.colorbar()
t.set_label("spring",fontsize=15)
plt.show()
8
[14]: plt.figure(figsize=(15,6))
day=[1,2,3,4,5,6]
no=[2,4,1,6,8,4]
no2=[7,3,4,9,1,0]
c=[13,54,32,78,95,36]
sizes=[145,108,165,254,179,197]
plt.scatter(day,no,c=c,s=sizes,cmap='GnBu',
marker='^',edgecolors='black',linewidths=1)
plt.colorbar()
plt.scatter(day,no2,c=c,s=sizes,cmap='gist_gray',
marker='D',edgecolors='black',linewidths=1)
plt.title("Scatter Plot",fontsize=15)
plt.xlabel("Day",fontsize=15)
plt.ylabel("No",fontsize=15)
9
plt.colorbar()
plt.show()
[ ]:
10
stack-plot
1 Stack Plot
[1]: import matplotlib.pyplot as plt
[2]: x=[1,2,3,4,5,6]
area=[4,3,3,7,4,1]
plt.stackplot(x,area)
plt.show()
1
[3]: x=[1,2,3,4,5,6]
area1=[4,3,3,4,5,6]
area2=[1,3,2,3,5,6]
area3=[4,1,2,4,5,7]
l=['Area-1','Area-2','Area-3']
plt.stackplot(x,area,area1,area2,labels=l
,colors=['#8FCB9B','#FFBA08','#3F88C5'])
plt.legend(loc=2)
plt.show()
[5]: plt.figure(figsize=(15,15),facecolor='lightcyan')
x=[1,2,3,4,5,6]
area1=[4,3,3,4,5,6]
area2=[1,3,2,3,5,6]
area3=[4,1,2,4,5,7]
l=['Area-1','Area-2','Area-3']
plt.subplot(3,1,1)
2
plt.stackplot(x,area1,area2,area3,labels=l,baseline="zero")
plt.subplot(3,1,2)
plt.stackplot(x,area1,area2,area3,labels=l,baseline="sym")
plt.subplot(3,1,3)
plt.stackplot(x,area1,area2,area3,labels=l,baseline="wiggle")
plt.suptitle('Python')
plt.legend(loc=2)
plt.figlegend()
plt.show()
3
[ ]:
4
stem-plot
1 Stem Plot
[1]: import matplotlib.pyplot as plt
[5]: x=[1,2,3,4,5]
y=[2,4,6,2,7]
plt.stem(x,y)
plt.show()
1
[8]: x=[1,2,3,4,5]
y=[2,4,6,2,7]
plt.stem(x,y,linefmt=":",markerfmt='rD',bottom=1)
plt.show()
[9]: x=[1,2,3,4,5]
y=[2,4,6,2,7]
plt.stem(x,y,linefmt=":",markerfmt='rD',bottom=7)
plt.show()
2
[11]: x=[1,2,3,4,5]
y=[2,4,6,2,7]
plt.stem(x,y,linefmt=":",markerfmt='rD',bottom=1,
basefmt='g',label='Python',use_line_collection=False)
plt.legend()
plt.show()
3
[12]: x=[1,2,3,4,5]
y=[2,4,6,2,7]
plt.stem(x,y,linefmt=":",markerfmt='rD',bottom=1,
basefmt='g',label='Python',
use_line_collection=False,orientation='horizontal')
plt.legend()
plt.show()
4
[ ]:
5
step-plot
1 Step Plot
[1]: import matplotlib.pyplot as plt
[11]: x=[1,2,3,4,5]
y=[1,2,3,4,5]
plt.step(x,y,color='r',marker='D',ms=10,mfc='y',label='Python')
plt.title('Step Plot')
plt.xlabel('X - Axis')
plt.ylabel('Y - Axis')
plt.legend(loc=2)
plt.grid()
plt.show()
1
[ ]:
2
subplot-savefig
[14]: x=[1,2,3,4]
y=[2,3,4,1]
x1=[10,20,30]
x2=['A','B']
y2=[35,23]
plt.subplot(2,2,1)
plt.plot(x,y,color='r')
plt.subplot(2,2,2)
plt.pie(x1,colors='y')
plt.subplot(2,2,3)
plt.pie([2],colors='r')
plt.subplot(2,2,4)
plt.bar(x2,y2)
plt.show()
1
[20]: # if you want to save
x=[1,2,3,4]
y=[2,3,4,1]
x1=[10,20,30]
x2=['A','B']
y2=[35,23]
plt.subplot(2,2,1)
plt.plot(x,y,color='r')
plt.subplot(2,2,2)
plt.pie(x1,colors='y')
plt.subplot(2,2,3)
plt.pie([2],colors='r')
plt.subplot(2,2,4)
plt.bar(x2,y2)
plt.savefig('Chart.pdf',dpi=20000,facecolor='lightgreen',
2
transparent=True,bbox_inches='tight')
plt.show()
[ ]:
3
text-add
[15]: x=[1,2,3,4]
y=[2,1,3,3]
plt.plot(x,y)
plt.text(x=3,y=2.5,s='Python',fontsize=13,style='italic',bbox={'facecolor':'y'})
plt.title('Python',fontsize=15)
plt.xlabel('4-Days',fontsize=15)
plt.ylabel('No.',fontsize=15)
plt.show()
1
[25]: x=[1,2,3,4]
y=[2,1,3,3]
plt.plot(x,y)
plt.text(x=3,y=2.5,s='Python',fontsize=13,style='italic',bbox={'facecolor':'y'})
plt.title('Python',fontsize=15)
plt.xlabel('4-Days',fontsize=15)
plt.ylabel('No.',fontsize=15)
plt.
↪annotate('Python',xy=(2,2),xytext=(1,2),arrowprops=dict(facecolor='r',shrink=78))
plt.legend(['UP'],facecolor='lightgreen',edgecolor='r',framealpha=0.
↪5,shadow=True)
plt.show()
2
[ ]:
3
ticks
1 Ticks
[1]: import matplotlib.pyplot as plt
[6]: x=[1,2,3,4,5]
y=[3,1,5,2,4]
plt.plot(x,y)
plt.show()
[9]: x=[1,2,3,4,5]
y=[3,1,5,2,4]
1
plt.plot(x,y)
#plt.xticks(x,labels=['A1','A2','A3','A4','A5'])
plt.xticks(x)
plt.yticks(y)
plt.show()
[10]: x=[1,2,3,4,5]
y=[3,1,5,2,4]
plt.plot(x,y)
# plt.xticks(x,labels=['A1','A2','A3','A4','A5'])
# plt.xticks(x)
# plt.yticks(y)
plt.xlim(0,10)
plt.ylim(0,10)
plt.show()
2
[11]: x=[1,2,3,4,5]
y=[3,1,5,2,4]
plt.plot(x,y)
plt.axis([0,10,0,7])
plt.show()
3
[ ]:
4
Exercises
Write a Python program to draw a line with suitable label in the x axis, y axis
and a title.
Write a Python program to draw a line using given axis values with suitable
label in the x axis , y axis and a title.
import numpy as np
import matplotlib.pyplot as plt
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
import matplotlib.pyplot as plt
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.xticks(x_pos, x)
plt.minorticks_on()
plt.show()
Write a Python program to create bar plot of scores by group and gender. Use
multiple X values on the same chart for men and women.
Sample Data:
Means (men) = (22, 30, 35, 35, 26)
Means (women) = (25, 32, 30, 35, 29)
import numpy as np
import matplotlib.pyplot as plt
# data to plot
n_groups = 5
men_means = (22, 30, 33, 30, 26)
women_means = (25, 32, 30, 35, 29)
# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by person')
plt.xticks(index + bar_width, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.legend()
plt.tight_layout()
plt.show()
Write a Python program to add textures (black and white) to bars and wedges.
ax = fig.add_subplot(111)
for i in range(len(patterns)):
ax.bar(i, 3, color='white', edgecolor='black',
hatch=patterns[i])
plt.show()
Write a Python programming to create a pie chart with a title of the popularity
of programming Languages.
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
import matplotlib.pyplot as plt
# Plot data
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
#colors = ['red', 'gold', 'yellowgreen', 'blue', 'lightcoral',
'lightskyblue']
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b"]
# explode 1st slice
explode = (0.1, 0, 0, 0, 0, 0)
# Plot
plt.pie(popuratity, explode=explode, labels=languages,
colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct
2017 compared to a year ago", bbox={'facecolor':'0.8', 'pad':5})
plt.show()
Write a Python program to draw a scatter plot with empty circles taking a
random distribution in X and Y and plotted against each other.
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(50)
y = np.random.randn(50)
plt.scatter(x, y, s=70, facecolors='none', edgecolors='g')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Write a Python program to draw a scatter plot using random distributions to
generate balls of different sizes.
import math
import random
import matplotlib.pyplot as plt
# create random data
no_of_balls = 25
x = [random.triangular() for i in range(no_of_balls)]
y = [random.gauss(0.5, 0.25) for i in range(no_of_balls)]
colors = [random.randint(1, 4) for i in range(no_of_balls)]
areas = [math.pi * random.randint(5, 15)**2 for i in
range(no_of_balls)]
# draw the plot
plt.figure()
plt.scatter(x, y, s=areas, c=colors, alpha=0.85)
plt.axis([0.0, 1.0, 0.0, 1.0])
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Write a Python program to draw a scatter plot comparing two subject marks of
Mathematics and Science. Use marks of 10 students.
Test Data:
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
import matplotlib.pyplot as plt
import pandas as pd
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.scatter(marks_range, math_marks, label='Math marks', color='r')
plt.scatter(marks_range, science_marks, label='Science marks',
color='g')
plt.title('Scatter Plot')
plt.xlabel('Marks Range')
plt.ylabel('Marks Scored')
plt.legend()
plt.show()