0% found this document useful (0 votes)
2 views93 pages

Matplotlib Merged Merged

Matplotlib is a powerful Python library for data visualization that allows users to create a variety of static and interactive plots, including line, scatter, bar, and histogram plots. It is easy to use, highly customizable, and integrates well with other Python libraries like NumPy and Pandas. The library is open-source and supports a wide range of platforms, making it a popular choice for scientific computing and data analysis.

Uploaded by

yashvikkhatri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views93 pages

Matplotlib Merged Merged

Matplotlib is a powerful Python library for data visualization that allows users to create a variety of static and interactive plots, including line, scatter, bar, and histogram plots. It is easy to use, highly customizable, and integrates well with other Python libraries like NumPy and Pandas. The library is open-source and supports a wide range of platforms, making it a popular choice for scientific computing and data analysis.

Uploaded by

yashvikkhatri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

Matplotlib

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.

Data visualization is the graphical representation of information and data.

Can be achieved using visual elements like figures, charts, graphs, maps.

Converting complex data into an easy to understand representation

Data visualization can perform below tasks:

o It identifies areas that need improvement and attention.

o It clarifies the factors.

o It helps to understand which product to place where.

o Predict sales volumes.

Matplotlib

Matplotlib is one of the most powerful tools for data visualization in


python.

Matplotlib is an incredibly powerful and beautiful 2-D plotting library.

Install Matplotlib
The python package manager pip is also used to install matplotlib. Open
the command prompt window, and type the following command:

pip install matplotlib

The General Concept of Matplotlib

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

To verify that matplotlib is installed properly or not, type the following


command includes calling .__version __ in the terminal.

1. import matplotlib
2. matplotlib.__version__

Syntax for importing matplotlib

Import matplotlib.pyplot as plt


Syntax for plotting the graph

plt.plot(x,y)

Syntax for showing the plot:

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.

2. Customizability: Matplotlib provides a high degree of customization for


visualizations. Users can customize every aspect of the plot, including colors, fonts,
labels, and axes.

3. Compatibility: Matplotlib is compatible with a wide range of platforms and


operating systems. It can be used on Windows, Linux, and macOS.

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.

6. Interactive visualizations: Matplotlib provides tools for creating interactive


visualizations using widgets and animations.

7. Publication-quality plots: Matplotlib provides tools for creating publication-


quality plots that meet the standards of scientific publications.

8. Large community: Matplotlib has a large community of users and developers who
contribute to its development and provide support to users.

9. Extensibility: Matplotlib is highly extensible and allows users to create custom


plot types and styles.

10. Free and open-source: Matplotlib is free to use and distribute under the BSD
license.

There are several reasons why Python Matplotlib is a


popular choice for data visualization:

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.

3. Integration with other Python libraries: Python Matplotlib integrates seamlessly


with other popular Python libraries such as NumPy and Pandas. This makes it easy to
import data from these libraries and create visualizations that are tailored to specific
data sets.

Matplotlib is a popular data visualization library in Python


that provides a wide range of 2D and 3D plots for scientific
and engineering applications. Here is a list of some of the
most commonly used plots in Matplotlib:

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.

4. Histogram: A histogram displays the distribution of a dataset by dividing it into


bins and counting the number of observations in each bin. It is useful for visualizing
the shape of a distribution.

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

June 19, 2023

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

June 19, 2023

1 Box Plot
[1]: import matplotlib.pyplot as plt

[2]: plt.colormaps() # give color cmap color theme

[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

June 19, 2023

1 Fill Between Plot


[11]: import matplotlib.pyplot as plt
import numpy as np

[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.fill_between(x,y,color='y',where=(x>=2) & (x<=4),alpha=0.4)

plt.title('Step Plot')
plt.xlabel('X - Axis')
plt.ylabel('Y - Axis')
plt.show()

3
[ ]:

4
histogram-plot

June 19, 2023

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

June 19, 2023

1 Imshow
[1]: import matplotlib.pyplot as plt
import matplotlib.image as mpimg

[3]: img=mpimg.imread('wallpaperflare.com_wallpaper (4).jpg')

img.shape

[3]: (1080, 1920, 3)

[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
[ ]:

[ ]:

[12]: import matplotlib as mpl


import matplotlib.pyplot as plt

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)

print(f'mpl version: {mpl.__version__},\nnumber of cmaps: {n_cmaps}')

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)

last_iteration = index == n_cmaps-1


if (row==N_ROWS-1 and col==N_COLS-1) or last_iteration:
plt.tight_layout()
#plt.savefig('colormaps'+str(index)+'.png')
plt.show()
if last_iteration: return
index += 1

plot_all_cmaps()

mpl version: 3.5.2,


number of cmaps: 166

3
4
[ ]:

5
pie-plot

June 19, 2023

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

June 19, 2023

[1]: ! pip install matplotlib

Requirement already satisfied: matplotlib in


c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(3.5.2)
Requirement already satisfied: pillow>=6.2.0 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (9.2.0)
Requirement already satisfied: pyparsing>=2.2.1 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (3.0.9)
Requirement already satisfied: numpy>=1.17 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (1.23.1)
Requirement already satisfied: cycler>=0.10 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (0.11.0)
Requirement already satisfied: kiwisolver>=1.0.1 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (1.4.4)
Requirement already satisfied: fonttools>=4.22.0 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (4.34.4)
Requirement already satisfied: packaging>=20.0 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (21.3)
Requirement already satisfied: python-dateutil>=2.7 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from matplotlib) (2.8.2)
Requirement already satisfied: six>=1.5 in
c:\users\prashant\appdata\local\programs\python\python310\lib\site-packages
(from python-dateutil>=2.7->matplotlib) (1.16.0)

[notice] A new release of pip available: 22.2 -> 23.1.2


[notice] To update, run: python.exe -m pip install --upgrade pip

[6]: import matplotlib.pyplot as plt

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.title('Day VS Data ',fontsize=17)


plt.xlabel('Days',fontsize=14)
plt.ylabel('Data',fontsize=14)

plt.show()

[ ]:

2
scatter-plot

June 19, 2023

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

June 19, 2023

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

June 19, 2023

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

June 19, 2023

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

June 19, 2023

1 Subplot & Save fig


[1]: import matplotlib.pyplot as plt

[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

June 19, 2023

[1]: import matplotlib.pyplot as plt

[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

June 19, 2023

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.

import matplotlib.pyplot as plt


X = range(1, 50)
Y = [value * 3 for value in X]
print("Values of X:")
print(*range(1,50))
print("Values of Y (thrice of X):")
print(Y)
# Plot lines and/or markers to the Axes.
plt.plot(X, Y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Draw a line.')
# Display the figure.
plt.show()

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 matplotlib.pyplot as plt


# x axis values
x = [1,2,3]
# y axis values
y = [2,4,1]
# Plot lines and/or markers to the Axes.
plt.plot(x, y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Sample graph!')
# Display a figure.
plt.show()
Write a Python program to plot two or more lines on same plot with suitable
legends of each line.

import matplotlib.pyplot as plt


# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1")
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2")
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title of the current axes.
plt.title('Two or more lines on same plot with suitable legends ')
# show a legend on the plot
plt.legend()
# Display a figure.
plt.show()
Write a Python program to plot several lines with different format styles in one
command using arrays.

import numpy as np
import matplotlib.pyplot as plt

# Sampled time at 200ms intervals


t = np.arange(0., 5., 0.2)

# green dashes, blue squares and red triangles


plt.plot(t, t, 'g--', t, t**2, 'bs', t, t**3, 'r^')
plt.show()
Write a Python programming to display a bar chart 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

x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']

popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]

x_pos = [i for i, _ in enumerate(x)]

plt.bar(x_pos, popularity, color='blue')

plt.xlabel("Languages")

plt.ylabel("Popularity")

plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct


2017 compared to a year ago")

plt.xticks(x_pos, x)

# Turn on the grid

plt.minorticks_on()

plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')

# Customize the minor grid

plt.grid(which='minor', linestyle=':', linewidth='0.5',


color='black')

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

rects1 = plt.bar(index, men_means, bar_width,


alpha=opacity,
color='g',
label='Men')

rects2 = plt.bar(index + bar_width, women_means, bar_width,


alpha=opacity,
color='r',
label='Women')

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.

import matplotlib.pyplot as plt


fig = plt.figure()
patterns = [ "|" , "\\" , "/" , "+" , "-", ".", "*","x", "o", "O" ]

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()

You might also like