0% found this document useful (0 votes)
9 views8 pages

Essential Matplotlib Commands Guide

This document provides a comprehensive list of Python Matplotlib commands used for data visualization in the context of a Data Analytics course. It includes commands for various types of plots such as line, bar, scatter, histogram, pie, and more, along with explanations of their functionalities. Additionally, it covers advanced plotting techniques, including 3D charts, distribution plots, and annotations.

Uploaded by

Arpan Nandi
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)
9 views8 pages

Essential Matplotlib Commands Guide

This document provides a comprehensive list of Python Matplotlib commands used for data visualization in the context of a Data Analytics course. It includes commands for various types of plots such as line, bar, scatter, histogram, pie, and more, along with explanations of their functionalities. Additionally, it covers advanced plotting techniques, including 3D charts, distribution plots, and annotations.

Uploaded by

Arpan Nandi
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

Notes : Python Matplotlib Commands

Course Name : Data Analytics with Python

Content Provider : Data Science Lovers

MATPLOTLIB COMMANDS

1. import [Link] as plt # To import matplotlib library.

2. %matplotlib inline # To show the plots automatically without need to enter [Link]( ).

3. from matplotlib import style , [Link](“ggplot”) # For style purpose.

4. [Link]([‘name’],loc= ‘upper left’ /1/2/3/4, title=’legend title ) # To show the labels of the lines.

5. [Link](True, color = ‘ ’) # To show the grid.

6. [Link]([ ] ,rotation='vertical'/90,size=10, color=’red’) , [Link]([Link](0,20,2), [ ])


#To shows the ticks on x-axis and y-axis.

7. [Link](‘Year’) , [Link](‘Sales’) # To show the labels on x-axis and y-axis.

8. [Link](‘Year Sales Diagram’, fontsize=24) # To show the title on the graph.

9. [Link]().get_xaxis().set_visible(False) # To remove the x-axis.

10. [Link]().get_yaxis().set_visible(False) # To remove the y-axis.

11. [Link](100) , [Link](20) # To set the starting point of graph, x=100 & y=20.

12. [Link](figsize=(10, 20)) ; [Link][‘[Link]’]=(18,20) ; [Link]( ).add_axes([0,0,2,1])


# To adjust the figure size.

13. [Link]('plot_name.png', bbox_inches='tight', format= ‘pdf’) # To save the graph plot.


14. [Link]['[Link]'] = ':' # To change the line style of graph.

15. [Link](kind= ‘optional’ ) # To draw a plot of all columns at once.

16. Line Plot - [Link]( x-elements, y-elements , ‘bo-’)

# Line graphs are used to show value of some items over time.

[Link]( df[‘Year’] , df[‘Sales’] ) , [Link]( [1,2,3,4], [21,34,56,39] ) ,

[Link]( a, b, color=‘g’, linewidth=2 , makersize = 10)

‘bo-’ → b = blue color , o = marker (*,.+sd) , - = Draws line

17. Bar Plot - [Link]( x-elements, y-elements )

# For Categorical Data….Bar graphs are used to make comparison between different categories.

[Link]( x , y , color = ‘bkgrc’ , label= ‘New’ , width = 0.7 ),

[Link](stacked=True)

18. Horizontal Bar Chart - [Link]( x-elements, y-elements )

# Bars will raise from x-value and goes up-to y values. [Link](stacked=True)

19. Scatter Plot - [Link]( x-elements, y-elements , color = ‘r’, s = 20 , edgecolor= ‘red’ . style='*-')

# It shows data as a collection of points. Predictor(Indep.) on x-axis & Target(Dep.) on y-axis.

20. Bubble Plot - [Link]( x-elements, y-elements , color = [Link](length of


column) , s = 20 , edgecolor= ‘red’ . style='*-')

# Same as scatter plot.

21. Histogram - [Link](data, bins= , color = ‘ ’ , rwidth = )

# Show frequency of data divided into intervals. It tends to show the distribution by grouping segments
together.

22. Stack Plot - [Link]( list1, list2, list3, list4 , color = ‘mcbr’ )

# It is generated by plotting different datasets vertically on top of one another.


23. Pie Chart - [Link](slices, labels= activities, colors = ‘bryg’, startangle= ,
shadow=True, explode=(0,0,0.1,0.2), autopct= ‘%1.1f%%’, pctdistance=0.75 ) .
Slices = [12,15,20,10] , activities = [‘eating’, ‘ sleeping’ , ‘working’, ‘playing’].

# Explode – To cut the slices out.


# Autopct – To show the % on the chart using string format.
# pctdistance – Distance of % from center
# Compare parts of data to the whole.

It shows the size of items(wedges) in one data series proportional to the sum of the items.

24. Box Plot - [Link]( ) , [Link](x='Cat_col' , y='Num_col', data=df,


showmean=True, vert=True/False, sym=’+/*’, meanline=True)

- This graph represents the min, max, median, first quartile & third quartile in the dataset.
- It shows how well distributed the data is in a dataset.
- In box plot, a box is plotted from Ist quartile to IIIrd quartile, a vertical line also goes through median.
‘showmeans=True’ indicates the mean point. ‘vert=True/False’ to show horizontal plot. ‘sym’ to change
outlier sign. ‘meanline=True’ to show the mean line.

25. Heat Map - [Link](df, cmap=‘RdBu’) , [Link]( )

- The darker shades of the chart represent higher values than the lighter shade.

26. 3D Charts

from mpl_toolkits.mplot3d import axes3d # To add a subplot to an existing 2d plot.


chart = [Link]()
chart3d = chart.add_subplot(111, projection='3d')

# Create some test data


x,y,z = axes3d.get_test_data(0.08)

# Plot a wireframe
chart3d.plot_wireframe(x,y,z, color='r', rstride=15, cstride=10)
[Link]()
27. SubPlot – To draw multiple plots in one figure.

Syntax : [Link](no._of_rows, no._of_columns, index_number)

28. Graph from Pandas directly :

[Link]( x = ‘Year’, y = ‘Sales’ , kind = “ line/scatter/box/area/stack/pie/bar”, figsize = (25,4),


color=['red', 'black', 'green', 'yellow', 'orange'] ).

df.Col_name.plot(style='*-' , figsize = (25,4)

- Pandas can make graphs by calling plot directly from the DF (using [Link]( ) ).
- Plots can be called by defining plot kinds.

29. Time Series Plot - [Link]( ) , where x = df.datetime_index , y = [Link]

30. Plotting two sets of data : [Link](x-elements1 , y-elements1) , [Link](x-elements2, y-elements2)

31. plt.fill_between(x-elements1, y-elements1, y-elements2, facecolor='green', alpha=1.5)


# Filling the space between datasets.
32. To draw the month/year wise sales on graph –

months = range(1,13) , [Link]( months , [Link](‘month/year_col’).sum( ) )


33. To check the relationship between two columns :

[Link]( x = ‘Col_1’ , y = ‘Col_2’ , data = df_name )

[Link]( x = ‘Col_1’ , y = ‘Col_2’ , hue = ‘Col_3’ , data = df_name , kind = ‘line’ , height = 5 , aspect
=3)

[Link](x = ‘Col_1’ , y = 'Col_2’ , data = df_name )

34. [Link](df_name) - It shows the relationship between all the columns with each other (correlation).

35. df.Col_name.plot( kind = ‘ ’) – To draw a plot between the indexes and a column.
[Link]( )

36. [Link](df.Col_name) # To show the value-counts in the form of bar graph.

37. To draw a Sine Wave Plot

x = [Link](0, 3 * [Link] , 0.1)


y = [Link](x)
[Link](x,y)

38. Adding Annotations ( Naming on plot sheet wrt to points )

[Link](xy=[2,1] , s = ‘first annotation at x=2 & y=1’)

[Link](xy=[4,6] , s = ‘second annotation at x=4 & y=6’)

39. To draw multiple lines on one graph

[Link](x,y, marker='o', color='g'),

[Link](x,z , marker='*', color='red')

[Link](x,t , marker='.', color='black')

40. To draw Linear Regression Graph

import seaborn as sns

[Link]( x = df.Col_x , y = df.Col_y ) ; # To see the correlation between two variables.


41. To draw Residual Plot # It represents the error between the actual values.

[Link]( df.Col_x , df.Col_y)

42. To draw Distribution Plot # It counts the predicted value versus the actual value.

ax1 = [Link]( df.Col_y , hist=False , color= ‘r’, label= ‘Actual Value’)

[Link]( yhat , hist=False , color= ‘b’ , label= ‘Fitted Values’ , ax = ax1 )

43. Pearson Correlation Heatmap : [Link]([Link]( ) , vmin=-1, vmax=1, center=0 )

44. To draw the Normal Distribution curve –


mu = 0.5 , sigma = 0.1
s = [Link](mu , sigma , 1000)

# Create the bins & histogram


count , bins , ignored = [Link](s , 20 , density = True)

# Plot the distribution curve


[Link](bins , 1/(sigma*[Link](2*[Link])) *
[Link]( - (bins - mu)**2 / (2*sigma**2)) , linewidth = 3, color = 'y')
[Link]()

45. To draw Binomial Distribution curve –

from [Link] import binom , import seaborn as sns

[Link](size=10, n=20 , p=0.8)

data_binom = [Link](n=20 , p=0.8, loc=0, size=1000)

ax = [Link](data_binom,
kde=True,
color='blue',
hist_kws={"linewidth":25 , 'alpha':1})

[Link](xlabel = 'Binomial' , ylabel = 'Frequency')

[Link]( )
46. To draw Poisson Distribution

from [Link] import poisson , import seaborn as sns

data_binom = [Link](mu=4, size=10000)

ax = [Link](data_binom,
kde=True,
color='r',
hist_kws = {'linewidth':25, 'alpha':1})

[Link](xlabel = 'Position' , ylabel='Frequency')

[Link]( )

47. To draw Bernoulli Distribution

from [Link] import Bernoulli , import seaborn as sns

data_bern = [Link](size=100, p=0.6)

ax = [Link](data_bern,
kde = True,
color='c',
hist_kws={'linewidth':25, 'alpha':1})

[Link](xlabel='Bernoulli', ylabel='Frequency')

[Link]( )

48. To draw a Chi-Square Distribution

from scipy import stats , import numpy as np

x = [Link](0, 10, 100)

fix, ax = [Link](1,1)

linestyles = [':','--','-.','-']

deg_of_freedom = [1,4,7,6]

for df, ls in zip(deg_of_freedom, linestyles):


[Link](x, [Link](x, df), linestyle=ls)

[Link](0, 10) , [Link](0, 0.4)

[Link]('Value') , [Link]('Frequency') , [Link]('Chi-Square Distribution')

[Link]()

49. Insert Image in Jupyter Notebook -- Convert the Cell to MarkDown > Edit Tab > Insert Image > Run

By – ROHIT GREWAL

You might also like