Matplotlib Starter: Import As Import As Import As
Matplotlib Starter: Import As Import As Import As
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])
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]
[14 17 10 9]
[ 0. 24.75 49.5 74.25 99. ]
4. Bar Chart
[0 1 2 3]
[ 4 21 50 42]
print(x,'\n\n',y)
[0 1 2 3]
[ 4 21 50 42]
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()
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
Out[34]: array([ 5, 15, 25, 35, 45, 55, 65, 75, 85, 95])
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']
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()
# for legend location: 'upper left', 'upper right', 'lower left', 'lower right'
# for legend location: 'upper center', 'lower center', 'center left', 'center righ
t'
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
In [207]: df.index.tolist()
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')
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)
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[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))
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
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)
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.
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/)