Matplotlib Starter
In [2]: import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
1. Plotting a line --> y=mx+c : m = (1/sqrt(3)) ; C=4; y=[1/sqrt(3)] x+ 4
In [5]: x=np.linspace(-5,5,11) # Taking 11 equal spaced data points between -5 to 5 includi
ng both, as x
print('x :', x,'\n')
y=(1/(3)**(0.5))*x+4
print('y: ',y)
plt.plot(x,y,'r--o',linewidth=2, markersize=8, label='first line')
# 'r--o': Red colored dashed line with circular dots representing data points.
plt.grid(True)
plt.show()
x : [-5. -4. -3. -2. -1. 0. 1. 2. 3. 4. 5.]
y: [1.11324865 1.69059892 2.26794919 2.84529946 3.42264973 4.
4.57735027 5.15470054 5.73205081 6.30940108 6.88675135]
Diving Deeper
In [68]: plt.figure(figsize=(6,6)) # For defining figure size(length and height)
# Defining title of the plot with differnt font & style options
plt.title('My first matplotlib Plot',fontsize=12,style='italic',fontweight='bold')
# Inside plot, pass x and y of each points as list/tuple/array
plt.plot(x,y,'r--o',linewidth=2, markersize=8, label='first line') # 'r--o': Red
colored dashed line with circular dots representing data points
# label -> Displayed in legend
plt.axvline(x=0,color='k',label='Y-axis') # line parallel to y-axis, Here line thro
gh x=0 i.e. y-axis itself.
plt.axhline(y=0,color='g',label='X-axis') # line parallel to x-axis, Here line thro
gh y=0 i.e. x-axis itself.
plt.xlabel('X-values')#,fontsize=12, style =..,fontweight=...) # For description be
lwo to the x axis
plt.ylabel('Y-values')#,fontsize=12, style =..,fontweight=...) # For the descripti
on left to the y axis
plt.legend(loc='upper left',fontsize=12) # Box displaying label of each differnt li
nes on the plot
# Writing text on any cordinate of the plot
plt.text(2, 0.3, 'X-Axis',fontsize=15, color='g',rotation='horizontal')
plt.text(-0.6,5.5, 'Y-Axis',fontsize=15, color='k',rotation='vertical')
plt.text(0,0,f'(0,0)',fontsize=15)
# Displaying particularly incremented xticks and yticks values on axes.
plt.xticks(np.arange(np.min(x), np.max(x)+1, 1.0))
plt.yticks(np.arange(-2, np.max(y)+1, 1.0))
plt.grid(True) # For making grid lines
plt.axis('equal') # equal scaling on both x and y axeses
plt.show()
plt.close() # All the defined properties are cleaned and no interferance with new p
lot
In [ ]: # For shaving the plot in your local system: provide the path, name and file type w
ith quality of image as dpi, before closing.
# plt.savefig(r'C:\Users\Ramendra\Desktop\Data\first_plot.png',dpi=300)
Documentation for further detail:
https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.plot.html
(https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.plot.html)
https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.text.html
(https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.text.html)
Rest Search on google.
2. Plotting Circle
Circle: X=rsin(theta) # y=rcos(theta) ## Polar eqn of circle
In [79]: theta=np.linspace(0,2*np.pi,100)
x=1*np.sin(theta)
y=1*np.cos(theta)
plt.figure(figsize=(4,4))
plt.plot(x,y,'r-',alpha=0.8) # alpha controls brightness of plot, max value is '1'.
plt.axis('equal') # making equal scale of both axes unit length
plt.axvline(x=0,color='k')
plt.axhline(y=0,color='k')
#plt.grid(True)
plt.axis([-1,1,-1,1])
Out[79]: (-1.0, 1.0, -1.0, 1.0)
https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.axis.html
(https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.axis.html)
3. Subplotting
We are going to make three different plots using following three dataset and then combine them in
Subplot.
Types of plots:
1.Plot
2.Scatter plot
3.Histogram Plot
In [105]: np.random.seed(0)
data1=np.array([0,2,2,6,4,10,6,14,8,18])
data2=np.random.randint(0,18,20)
data3=np.random.randint(0,100,50)
print(data1,'\n')
print(data2,'\n')
print(data3)
[ 0 2 2 6 4 10 6 14 8 18]
[12 15 0 3 3 7 9 4 6 12 1 6 7 14 17 5 13 8 9 16]
[69 79 47 64 82 99 88 49 29 19 19 14 39 32 65 9 57 32 31 74 23 35 75 55
28 34 0 0 36 53 5 38 17 79 4 42 58 31 1 65 41 57 35 11 46 82 91 0
14 99]
In [107]: ## Plotting Data 1
plt.plot(data1,'r--*',label='steps')
plt.show()
# Note : If we don't pass both x and y sequence,
# the passed sequence is taken as y and default x values are taken starting from 0
, having increment of 1.
In [112]: ## plotting data2
x=np.arange(1,21)
# for plotting scatter plot we need both x and y ,thus x is generated using numpy a
bove
plt.scatter(x,data2,label='scatter',color='g',marker='*',alpha=0.8)
plt.show()
In [109]: ### plotting data 3
plt.hist(data3,bins=10,color='g',edgecolor='r',label='hist')#,histtype='stepfille
d')
plt.show()
counts, bins = np.histogram(data3,4)
print(counts,'\n',bins)
[14 17 10 9]
[ 0. 24.75 49.5 74.25 99. ]
Combining all three plots and making subplots
In [111]: fig=plt.figure(figsize=(15, 8))
fig.subplots_adjust(hspace=0.6, wspace=0.3)
########## Plot ########
ax1=fig.add_subplot(2,2,1)## figure should have 2X2 or utp 4 fig,this is first of f
our
ax1.plot(data1,'r--*',label='Line')
ax1.set_title('Step plot')
ax1.legend(loc='upper left')
ax1.set(xlabel='X_values', ylabel='Y_values')
########## Scatter Plot ##########
ax2=fig.add_subplot(2,2,2)
ax2.scatter(np.arange(20),data2,label='Scater',color='g',s=25,marker='*',alpha=0.9)
ax2.set_title('Scatter Point')
ax2.legend(loc='best')
ax2.set(xlabel='X_Values', ylabel='Y_Values')
######## Histogram plot #############
ax3=fig.add_subplot(2,2,3)
ax3.hist(data3,bins=10,alpha=0.9,color='g',edgecolor='r',label='Hist')
ax3.set_title('Histogram')
ax3.legend(loc='best')
ax3.set(xlabel='X_Range', ylabel='Count')
plt.show()
plt.close()
4. Bar Chart
Simple Bar Chart:
In [138]: np.random.seed(8)
x = np.arange(4) # [0, 1, 2,3]
y = np.random.randint(1, 51, len(x))
print(x,'\n\n',y)
plt.bar(x, y)
[0 1 2 3]
[ 4 21 50 42]
Out[138]: <BarContainer object of 4 artists>
In [139]: np.random.seed(8)
x = np.arange(4) # [0,1,2,3]
y = np.random.randint(1, 51, len(x)) # 4 values in [1, 51]
xticklabels = ['2020', '2021', '2022', '2023'] ### ??
# Plot bar chart
plt.bar(x, y, tick_label=xticklabels) # Bar chart with labels
# default bar width is 0.8, from x-0.4 to x+0.4
plt.title('Projected Admission Chart')
plt.xlabel('Year')
plt.ylabel('Student Admission')
plt.show()
print(x,'\n\n',y)
[0 1 2 3]
[ 4 21 50 42]
Bar Chart (Grouped)
In [147]: ## Data setting :> x and y
x = np.arange(3) # [0, 1,2]
y1 = np.array([1, 6, 2])
y2 = np.array([2, 2, 1])
y3 = np.array([3, 3, 1])
x_ticklabels = ['2021', '2022', '2023']
y_colors = ['g','b','m']
y_labels = ['Item1', 'Item2', 'Item3']
bar_width = 0.2
# Set the width in x for grouped bars
plt.bar(x, y1, bar_width, color=y_colors[0], label=y_labels[0],tick_label=x_ticklab
els)
plt.bar(x+bar_width, y2, bar_width, color=y_colors[1], label=y_labels[1])
plt.bar(x+2*bar_width, y3, bar_width, color=y_colors[2], label=y_labels[2])
plt.xlabel('Year')
plt.ylabel('Sales')
plt.title('Projected Grouped Bar Chart')
plt.legend()
plt.show()
Bar Chart (Stacked)
In [146]: ## Data setting :> x and y
x = np.arange(3) # [0, 1,2]
y1 = np.array([1, 6, 2])
y2 = np.array([2, 2, 1])
y3 = np.array([3, 3, 1])
x_ticklabels = ['2021', '2022', '2023']
x_ticklabels = ['2021', '2022', '2023']
y_colors = ['g','b','m']
y_labels = ['Item1', 'Item2', 'Item3']
############
plt.bar(x, y1, color=y_colors[0], tick_label=x_ticklabels, label=y_labels[0])
plt.bar(x, y2, bottom=y1, color=y_colors[1], label=y_labels[1])
plt.bar(x, y3, bottom=y1+y2, color=y_colors[2], label=y_labels[2])
plt.xlabel('Year')
plt.ylabel('Sales')
plt.title(' Sales-Stacked Bar Chart')
plt.legend()
Out[146]: <matplotlib.legend.Legend at 0xacefba8>
5. Histogram plot revisit
In [170]: y = np.random.normal(65, 15, 500) # This generates 500 normally distributed numbers
having mean ~65 and std~15.
#print(y)
print('mean :',np.mean(y))
print('std_dev :',np.std(y))
mean : 66.10104731590789
std_dev : 14.987483789435565
In [32]: np.random.randint(10,20,5) # check this?
Out[32]: array([14, 15, 15, 11, 12])
In [33]: np.random.rand(10) # check this?
#https://numpy.org/doc/1.18/reference/random/generated/numpy.random.rand.html
Out[33]: array([0.07426411, 0.05669272, 0.41670689, 0.39972597, 0.26274139,
0.5321438 , 0.79119057, 0.58087838, 0.43068341, 0.05382813])
In [34]: np.arange(5, 100, 10)# Check this?
Out[34]: array([ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95])
In [35]: list(range(0, 101, 10))
Out[35]: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
In [175]: y = np.random.normal(65, 15, 500) # Normal Distributed at mean and std dev
x= np.arange(5, 100, 10) # x=5, 15, 25, ...
xtick_labels = ['0-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-7
9', '80-89', '90-100']
# Setup bins and Plot
bins = range(0, 101, 10) # bins are [0, 10), [10, 20), [20,30)... [90, 100]
h=plt.hist(y, bins=bins, rwidth=0.8)
# rwidth: ratio of width of bar over bin
plt.xticks(x, xtick_labels, rotation=45)
plt.xlim(0, 100) # range of x-axis
plt.xlabel('Mark')
plt.ylabel('Number of Students')
plt.title('Histogram')
plt.show()
### Check It ####
print('Count : ',h[0])
print('Bins : ',h[1])
Count : [ 2. 1. 3. 16. 58. 107. 128. 110. 55. 15.]
Bins : [ 0 10 20 30 40 50 60 70 80 90 100]
6. Pie Chart
In [268]: x_labels = ['X1', 'X2', 'X3', 'X4', 'X5']
y = [50, 30, 60, 20, 30]
explode = (0, 0.1, 0, 0, 0) # "explode" the second slice by 0.1
#c=['r','g','b','m','k'] ### for passing your own color
plt.pie(y, labels=x_labels, explode=explode,shadow=False, startangle=90)#,colors=c)
plt.axis('equal') # Draw a circle
plt.title('Pie Chart')
plt.show()
7. Trignometric Function plot with few more setting options
In [151]: x = np.linspace(-2*np.pi, 2*np.pi, 100)
#print(x)
# Generate y's
y = np.sin(3*x)/x
#print(y)
plt.plot(x, y, 'r-', label='sin(3*x)/x')
plt.legend()
Out[151]: <matplotlib.legend.Legend at 0xaaab278>
In [162]: # Generate x: linearly spaced in degree interval, both ends included
x = np.linspace(-2*np.pi, 2*np.pi, 100)
# Generate y's
y = np.sin(3*x)/x
# Get the axes handle for fine control. Axes uses set_xxx() setters for properties
ax = plt.subplot(1, 1, 1)
ax.plot(x, y, 'r-', label='sin(3*x)/x')
ax.legend()
# Remove the top and right border
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
# Move the bottom border to x=0 and left border y = 0
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))
# Set the x-tick position, locations and labels
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.set_xticks([-2*np.pi, -np.pi, 0, np.pi, 2*np.pi])
ax.set_xticklabels([r'$-2\pi$', r'$-\pi$', r'$0$', r'$+\pi$', r'$+2\pi$']) # Using
latex symbol
ax.set_title('Line Plot')
plt.show()
8. Setting font style using font_manager
In [2]: from matplotlib.font_manager import FontProperties
font=FontProperties()
font.set_family('cursive')# 'serif', 'sans-serif', 'cursive', 'fantasy', or 'monosp
ace'
font.set_name('Calibri') # # What is family here?
font.set_style('italic')# 'normal', 'italic' or 'oblique'.
font.set_size(30)
font.set_weight('bold')#'light', 'normal', 'regular', 'book', 'medium', 'roman', 's
emibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'
In [8]: data1=np.arange(10)
data2=np.array([0,2,2,6,4,10,6,14,8,18])
plt.plot(data1,'k-',label='default')
#plt.plot(data1,linestyle='-',color='k')
plt.plot(data2,'r*--',label='steps')
#plt.plot(data2,linestyle='--',color='r',marker='o')
plt.legend(loc='lower right',fontsize=12)
plt.title('My first matplotlib plot',c='g',fontproperties=font)#fontsize=12,style
='italic',fontweight='bold') #fontproperties=font)#
plt.xlabel('Stages',c='r',fontsize=16)
plt.ylabel('Value')#fontproperties=font
# for legend location: 'upper left', 'upper right', 'lower left', 'lower right'
# for legend location: 'upper center', 'lower center', 'center left', 'center righ
t'
Out[8]: Text(0, 0.5, 'Value')
9. Plotting with Pandas
Simple Plot
Bar Chart
Pie Chart
Box Plot ### Simple plot
https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.plot.html
(https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.plot.html)
In [218]: import pandas as pd
index=['one','two','three','four','five','six']
columns=pd.Index(['a','b','c','d'],name='Genus')
df=pd.DataFrame(np.arange(24).reshape(6,4)*2,index,columns)
df
Out[218]:
Genus a b c d
one 0 2 4 6
two 8 10 12 14
three 16 18 20 22
four 24 26 28 30
five 32 34 36 38
six 40 42 44 46
In [206]: df.index
Out[206]: Index(['one', 'two', 'three', 'four', 'five', 'six'], dtype='object')
In [207]: df.index.tolist()
Out[207]: ['one', 'two', 'three', 'four', 'five', 'six']
In [234]: df.plot()
C:\Users\hP\Anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py:1235:
UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_xticklabels(xticklabels)
Out[234]: <AxesSubplot:>
In [247]: plt.plot(df['a'])
plt.plot(df['b'])
plt.grid(True)
plt.title('My first matplotlib plot',fontsize=12,style='italic',fontweight='bold')
plt.xlabel('Stages',fontsize=12)
plt.ylabel('Value')
Out[247]: Text(0, 0.5, 'Value')
In [248]: df1=df.copy()
df1
Out[248]:
Genus a b c d
one 0 2 4 6
two 8 10 12 14
three 16 18 20 22
four 24 26 28 30
five 32 34 36 38
six 40 42 44 46
In [249]: df1.reset_index(inplace=True)
In [250]: df1
Out[250]:
Genus index a b c d
0 one 0 2 4 6
1 two 8 10 12 14
2 three 16 18 20 22
3 four 24 26 28 30
4 five 32 34 36 38
5 six 40 42 44 46
In [251]: df1.plot(kind='line',x='index',rot=45,y=['a','d'], title='DataFrame line plot',font
size=12,figsize=(6,4),grid=True)
plt.ylabel('Value')
C:\Users\hP\Anaconda3\lib\site-packages\pandas\plotting\_matplotlib\core.py:1235:
UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_xticklabels(xticklabels)
Out[251]: Text(0, 0.5, 'Value')
Bar Plot
In [252]: df1.plot(kind='bar',x='index',rot=10,y=['a','d'],fontsize=12,figsize=(6,4),grid=Fal
se)
Out[252]: <AxesSubplot:xlabel='index'>
In [253]: df1.plot(kind='barh',x='index',rot=10,y=['a','d'],fontsize=12,figsize=(6,4),grid=Fa
lse)
Out[253]: <AxesSubplot:ylabel='index'>
In [254]: df.plot.bar()
plt.ylabel('Values')
Out[254]: Text(0, 0.5, 'Values')
In [255]: df.plot.barh()
Out[255]: <AxesSubplot:>
In [256]: df1.plot(kind='bar',x='index',rot=10,y=['a','b','d'],fontsize=12,figsize=(6,4),grid
=False,stacked=True,alpha=1)
Out[256]: <AxesSubplot:xlabel='index'>
In [257]: df.plot.bar(stacked=True,alpha=1)
Out[257]: <AxesSubplot:>
Pie Chart
In [259]: df1
Out[259]:
Genus index a b c d
0 one 0 2 4 6
1 two 8 10 12 14
2 three 16 18 20 22
3 four 24 26 28 30
4 five 32 34 36 38
5 six 40 42 44 46
In [266]: df1[['a','b']].plot(kind='pie',subplots=True,figsize=(12,8),layout=(1,2))
Out[266]: array([[<AxesSubplot:ylabel='a'>, <AxesSubplot:ylabel='b'>]], dtype=object)
https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.plot.html
(https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.plot.html)
BOX PLOT
In [48]: df1 = pd.DataFrame(np.arange(50).reshape(10,5)*2, columns=['A', 'B', 'C', 'D', 'E'
])
df1
Out[48]:
A B C D E
0 0 2 4 6 8
1 10 12 14 16 18
2 20 22 24 26 28
3 30 32 34 36 38
4 40 42 44 46 48
5 50 52 54 56 58
6 60 62 64 66 68
7 70 72 74 76 78
8 80 82 84 86 88
9 90 92 94 96 98
In [50]: c = {'boxes': 'DarkRed', 'whiskers': 'DarkOrange','medians': 'DarkBlue', 'caps': 'G
ray'}
df1.plot.box()#color=c)
Out[50]: <matplotlib.axes._subplots.AxesSubplot at 0xc39a6c8>
In [51]: color = dict(boxes='DarkGreen', whiskers='DarkOrange',medians='DarkBlue', caps='Gra
y')
df1.plot(kind='box', color=color, sym='r+')
Out[51]: <matplotlib.axes._subplots.AxesSubplot at 0xc466c08>
https://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html (https://pandas.pydata.org/pandas-
docs/version/0.15.0/visualization.html)
This much for this module.Happy Learning.
Don't forget to follow me for more such stuff.
https://github.com/Rami-RK (https://github.com/Rami-RK)
https://www.linkedin.com/in/ramendra-kumar-57334478/ (https://www.linkedin.com/in/ramendra-kumar-
57334478/)