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

Matplotlib

Matplotlib is a popular Python library for data visualization that allows users to create static, animated, and interactive plots. Key functionalities include creating line graphs, bar charts, pie charts, histograms, and scatter plots, with customization options for colors, markers, and styles. The document provides examples and explanations for various plotting techniques and best practices for effective data representation.

Uploaded by

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

Matplotlib

Matplotlib is a popular Python library for data visualization that allows users to create static, animated, and interactive plots. Key functionalities include creating line graphs, bar charts, pie charts, histograms, and scatter plots, with customization options for colors, markers, and styles. The document provides examples and explanations for various plotting techniques and best practices for effective data representation.

Uploaded by

raiderguy157
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
MATPLOTLIB_NOTES-40 (0 Siva eee eee e seeded | ea ewer rmlmUc rmUcrmUchrmrmUchrCmUhF;]N SFC SFCULh/FH]hUhUh7MD EG SG OS i _ 4. WHAT Is MarpeLotiie ? = = Matplotlib is a powerful Python library used for data visualization. Tt_is used to create static, animated and interactive plots in Python: | Tt isthe most popular Library for plotting graphs in Python | i 2, INSTALLATION We can install matplotlib using pip Note: Make sure you have pip install matplotlib Python installed in your system. || 3. Importing MATPLOTLIB | The most commonly used module in matplotlib is pyplot. plt is an alias which is commonly used, import matplotlib. pyplot as plt 4, First GRAPH Let's create our first simple line graph || ExampLe Cope : Ourpur + import matplotlib-pyplot as plt ea a x = [4,2,3,4,5] % y= [10, 20, 30, 40, 50] — plt. plot (x, y) 8 = si plt. show () 4 | ° i ih ay S A 5 || EXPLANATION : X-axis «x and y are ‘the data points # plt. plot (x,y) is used to draw the line. + plt-show() is used to display the graph. | Key TAKEAWAYS : Next Topte —> ||_+ Matplotlib is used for data visualization. Line Chart with Title, | + pyplot module is used to create graphs X label and Y label. + [Link]() is used to plot line graphs. (Matplotlib Notes - 2) + Always use plt-show() to display the graph. Pee eae eee eee EEE MATPLOTLIB NOTES - 2 5. Muitzere Lines in One Graey Page No.: 2 We can plot more than one line on the same graph to compare multiple data sets. Date : 26 /05 /2024 EXAMPLE CODE : OuTpuT : import matplotlib. pyplot as plt Multiple Lines Example x = [4,2,3,4,5] & =e Line 1 yt = (10, 20, 30, 40, 50] 50 ick ae 2 y2 = [50, 40, 30, 20, 10] plt. plot (x, y1, label = ‘Line 1') 3” [Link] (x, y2, label = ‘Line 2') 8 30 plt. title (‘Multiple Lines Example’) is [Link](' X-axis’) [Link](' Y-axis") ac plt-legend() —# show legend plt. grid (True) 4 2 3 a 5 plt-show() Xoasis EXPLANATION : + We plotted two lines (yi and y2) on the same graph. + label is used to name the lines + [Link]() is used to show the legend (names of lines) + [Link](True) adds grid lines to the graph ae: Legends are useful when we have multiple Lines or plots to understand which line represents which data. 6. Line Covor We can change the color of lines in our plot. EXAMPLE Cope : Output : import matplotlib. pyplot as ple x= [4,2,3,4,5] y = [10, 20, 30, 40, 50] [Link] (x,y, color = ‘green’, label = ‘Green Line’) [Link] (x, y, color = ‘red’, Linestyle = '--', label = "Red Dashed Line’) pit. title (*Line Color Example’) pit. label (°X-azis’) pit. ylabel ("Y-azis') Line Color Example pit. Legend) pit. grid (True) pit. show() EXPLANATION : Common Couor NAMES : = color parameter is used to set the color of the Line or ee 7 red', ‘green’, ‘blue’, ‘black’, ‘orange’, + Linestyle = '=-' makes the line dashed. + We can use many color names or codes ‘purple’, ‘brown’, ‘pink’, ‘gray’ etc SCCoVeeevevevevvedud?D eeeesveveevoeeeeveees | MATPLOTLIB NOTES-3 [bisa F Markers In LINE Pier We can use markers to highlight each data point in the line. Markers make the graph more visible and attractive. Example Cove : Output : import matplottib. pyplot as plt Line Plot with Markers z= [1,2,3,4, 5] 60 y = (10, 20, 30, 40, 50] 50 plt. plot (x,y, marker='0', color ="b', im markersize = 8, markeredgecolor ='r', fs markerfacecolor = "yellow', linewidth=2) $30 plt. title (‘Line Plot with Markers’) ia plt. xlabel (*X-axis') plt. ylabel ("Y-azis') 10 pit. gid (True) ° T z 5 r i plt. show () con EXPLANATION : © marker = 'o' uses circle marker on each point * color = 'b* sets the line color to blue. + markersize controls the size of the marker: s+ markeredgecolor sets the edge color of the marker + markerfacecolor sets the fill color of the marker. + linewidth sets the thickness of the line. 8. Line STYLE We can change the style of the lint using Linestyle parameter. ExameLe Cope : Output : import matplottib. pyplat as plé Line Styles Example z= [1,2,3,4,5] = [10, 20, 30, 40, 50] pltsplot (x, y, Linesty! lt. plot (x, y, Linestyle pit. plot (x,y, Linesty label = "Dotted Line’) pit. plot (x,y, Linesty + label = Dash-Dot Line’) [Link] (‘Line Styles Example’) plt-alabel (’X-azis') plt. ylabel ('Y-oxis') pit. legend () ple. grid (True) ple. show() label = "Solid. Line") label = "Dashed Line’) EXPLANATION | * Linestyle controls the style of the Line. Solid line (default) { Note ; | We can conitine color, marker and line style | Lae | together to make our plots more effective | {and easy to understand. WS ! Dotted line Dash-Dot Line cs 9g. MATPLOTLIB NOTES - 4 Page Ni Date 28 / 05 / 2024 Bag CHart (Verticat) - [Link]() We can create bar charts using [Link](). It is used to compare discrete categories. eeeeeede. Examete Cope : Output : import matplotlib. pyplat as plt Monthly Sales Bar Chart categories = ["Jan', "Feb', ‘Mar’, ‘Apr’, ‘May "] é sales = [20, 35, 30, 45, 40] 50 plt. bar (categories, sales, color = ‘skyblue’, B40 edgecolor = 'black', width = 0.6) = [Link] (Monthly Sales Bar Chart") &” plt. xlabel ("Month ) 4 20 [Link] (“Sales (in 1000s)') ay 10 [Link] (axis = 'y', linestyle = '=-', alpha = 0.7) ple show () eS eA May Month EXPLANATION : + [Link]() is used to create vertical bar chart + categories are shown on the x-axis and sales on the y-axis. + color sets the fill color of bars + edgecolor gives border color to bars + width controls the width of bars. grid (axis ="y') adds horizontal grid lines. 10. Horizontal Bag CHART - plt. barh() Bar chart is best Sor comparing values across different categories. © We can create horizontal bar chart using plt. barh(). Exampce Cove : Output : import matplatlib. pyplat as ple products = ['Laptop!, ‘Mobile’, "Tablet', “Smarbuateh'] sales = £550, 750, 300, 450] plt-barh (products, sales, color = ‘lightgreen’, ‘edgecolor = black!) plt title ("Product Sales (Horizontal Bar Chart) ’) [Link] ("Sales (in units)") [Link] (Products) plt. grid (axis = 'x', Linestyle = pt shows () alpha = 0.7) CPO POTSTHHHHHHHHHHHHHHHHHKHHHKHEKEKEEY V Both are useful for comparing categorical data, EXPLANATION : orale ashe al tee) ee ere ere + categories are shown on the y-axis and values on the x-axis + Tk is useful when category names are long Key TAKEAWAYS V [Link]() > Vertical bar chart VY [Link]() > Horizontal bar chart J Product Sales (Horizontal Bar Chart) a ; 3 Da a a a eee Sales (in units) Common Pagamerers : Sets the color of bors + Sots border color of bars Sets width of bars color cedgecolor width alabeL(), ylabel() : Sets axis labels title() gra) ws Sets the ttle of the chart + Adds grid lines Pee eee ee eee eee eeed ees bsddddddddsdidilildidd MATPLOTLIB NOTES -5 41. Pre Cwart - [Link]() We can create pie charts using [Link](). It relationship Example Cove : Page No.: 5 Date : 29 / 05 / 2024 is used to show part-to-whole Output : import matplottib. pyplot as plt labels = ['Python', ‘Excel’, ‘SQL’, "Power BI’, ‘Other"] sizes = [35, 25, 20, 45, 5] colors = ['#4CAFSO", '#2496F3', “#FFCLOT", "#9¢2780', '#FF5722'] [Link] (sizes, labels = labels, colors = colors, autopet = "%1.1f%%', startangle » 90, shadow = True, explode = (0, 0, 0.4, 0, 0)) plt. title (‘Skills Distribution’) [Link](‘equal') # Equal aspect ratio ensures circle shape plt. show ( Skills Distribution. EXPLANATION : + labels Names shown for each slice. + sizes Values for each category + colors Colors for the slices + autopet Shows percentage on each slice + startongle Sets the starting angle of the pie chart + shadows Adds a shadow effect to the pie chart + explode Separates Cexplodes) the slice(s) + axis equal") : Ensures pie chart is drawn as a circle (not oval) OTHER UseFUL OPTIONS IN PIE CHART 4. Wim Pencenrace 2. Be 2 plt pie sizes, labels = labels, | explode = (0.1, 0, 0.4, eutopet = "A. Af8%") 0, 0.1) > Ine: Pie charts ave best used then you want to show the percentage contribution of categories in whole. wu 3. Womsour Lapens 4, Donut Cuaar pt pie sizes, labels = None, cutopet = "%14f%2") pit. pie (sizes, labels = labels, lwedgeprops = {'width’:0.4}, cutopet = "%[Link]%2") Other Power Bl Python sa. Excel Key TAKEAWAYS : WHEN To use Pre CHART ? oe ee 1) ven you want to show parts of a whole. VY autopet shows percentage of each slice |p Aedes peat aly V startangle rotates the pit chart le aes ent es Y explode is used to highlight important slice(s) ar ee ke enaee ae VY axis (‘equal’) keeps the pie chart in circular shape. | i Survey results, ete ; vee eee MATPLOTLIB NOTES-6 = [r= 12. Histogram - [Link]() Date : 30 / 05 /2024 We can create histogram to show the distribution of a continuous data. It groups the data into bins (ranges). Exampte Cope : Output : import matplottib. pyplot as ple import numpy as np # Generate some random data [Link].(0) # for reproducibility data. » np random normal(loe = 50, scale = 10, size « 1000) # Plot histogram plt-hist (data, bins + 15, color» ‘skyblue’, edgecalor = black’) plt-title (‘Histogram of Random Data") ple. alabel ("Value") plt. ylabel (“Frequency') [Link] (axis = 'y', Linestyle = plt. show () alpha = 0.7) Histogram of Random Data 2 30 «40 «50 60) «7080 EXPLANATION : + data : Random data generated using normal. distribution. + bins = 45 : Data is divided into 15 equal-width bins. * color : Fill color of the bars + edgecolor : Border color of the bars + grid(axis = 'y') : Adds horizontal grid. Lines 43. Scarter PLor - [Link]() Histogram is very useful to understand the distribution and pattern of data. We can create scatter plots to show relationship between two continuous variables Exameve Cope : Ourpur : Import matplottib. pyplot as plt import numpy os np # Sample date x = nprarray([t, 2, 3,4, 5,6, 7,8, 9, 10) y = np-orvay([2, 4, 5,4, 7,8, 7,9, 9, 14]) Scatter plot plt. scatter (2, y, color = ‘purple, marker = 'o!, 2» 60) plt. title ("Scatter Plot Example’) plt. label C°X Values’) plt. ylabel ("Y Values’ ) pit grid True, Linestyle = plt-show ©) +, alpha = 0.6) Scatter Plot Example X Values EXPLANATION : + pltccatter() is used to create scatter plot + marker = 'o! sets circular markers + 5 = 80 controls the size of markers + Grid helps to vead the values easily Common MARKERS IN SCATTER PLoT > i “4! > Circle ‘vi > Tangle Doon > Star ‘D> Diamond > Square “> Plus > Cross > Triangle Up | 'x" MAT PLOTLIB NOTES - (ae Date : 31 / 05 / 2024 14. Grip IN PLots - [Link]() We can add grid lines to the plot to make it easier to read values Example Cope : Output : import matplottib. pyplat as plt Line Plot with Grid P x= (1,2, 3, 4, 5, 6] be y= (10, 20, 25, 30, 35, 40] 40 # Plot line lt plot (2, y, marker ='0', color = teal’, ple: plat (a ng 40 linewidth» 2, label = 'Sales') % # Add grid ~ [Link] (True, linestyle = '--", color » ‘gray, * linewidth = 0.7) [Link]('Line Plot with Grid’) 4g ple. zlabel (* X-axis’) lt. label (* Y-axis! ° eee 1 2 3 4 5 6 ple. show () X-axis EXPLANATION : aa # [Link] (True) > Tums on the grid iG In: a # Linastyle='--' > Makes the grid dashed. (aes sores Pee tohen we want to match + color = ‘gray! > Sets the grid line color pst ee ea + Linewidth=0.7 > Sets the thickness of grid lines. u fF ae 15. Lecenp In Plots - [Link]() We can add a legend to the plot to identify different Lines, bars, ete Exampce Cove : Ourrur : import. matplettib. pyplot as ple Sales Comparison x= (1,2, 3, 4, 5] 40: = [40, 45, 20, 25, 30] y2 + (30, 25, 20, 15, 10] x0 plt-plot (a, yi, color="blue’, marker = ‘0! Unewidth2, Uebel = "Prouct A") ES [Link](a, y2, color = 'red", marker 3 Unewidth=2, label» ‘Product B°) plt-title ("Sales Comparison") 2 plt label ( ' X-axis’) [Link] (' Sales’ ) 0 [Link]() 4 show Legend ue : B [Link]() = = EXPLANATION: ‘LEGEND Postion Orrzons : Ss Labnk Und inde pl) te name each Un, | “Hf Ce pti) | ner gt? > atin ight im aoe pint oop ate conta right! Middl right eH tagendC) > Daag the pnd onthe plat fT UA’ TTS center Loft! > Hida , Lower Left! > Baton left coe) | Cathe fp = 2» Key TakEAWAYS : » V pltlagend() > Shouse a box that describes Unes/plots in the graph. YY These features make our plots more professional and easy to understand Teper o| COCK HHHHHHHHHSE oe MATPLOTLIB NOTES -8 16. SuspLots - [Link]() Page No. : 8 Date : o1 / 06 / 2024 We can create multiple plots in a single figure using subplots Te is very useful to compare different data side by side Exampue Cove : Oureur : import matplottib es pit a Plot 4 Plot 2 # Data for plate 60 60 == [1,23 4,5) é ¥ yt [10, 20, 30, 40, 50] y2= (50, 40, 30, 20, 10] * “ y2* (5, 10, 45, 20, 25] 5.30 ed # Create subplots (2 rows, 2 columas) 20 20 pltsubplot(2, 2,4) # Row 4, Col £ im pll-plat(e, yt, color="blue’, marker='e') i ple title (Plot 1°) =| ere war arrays plt-elabel (*X") E plt ylabel *Y") pltsubplot(2, 2,2) # Row 1, Col 2 ae RENCE pit plate, y2, color="red", marker ='s") 6 60 plt-title ('Plat 2") z [Link]( x") x pltglabel('Y") 40 40 pltsubplot(2, 2,3) # Row 2, Ct 5 | bs aa pltplot(e, ys, color= green’, markers"! plt. tithe (Plot 3°) at 29 pt alabel('X") 10 pl. ylabel('Y") F L_—_—_—— pltesubplot(2, 2,4) # Row 2, Col 2 234 8 A a es pit. bat Ce, ys, color = orange’) x x pit title ('Plat 4 (Bar Chart)') [Link]('X') pit. ylabel(°Y") plt tight tayout() a Adjust. spacing [Link] EXPLANATION 4 ple. subplot (2, 2, 1) means 2 rows, 2 columns and this is the 1 plot + We can add different types ef plots in each subplot. + [Link]-layout() adjusts spacing between plots automatically Suspior Syntax : plt. subplot (nrous, neols, index) + nrows > Number of rows + cols > Number of columns + index > Position of the plot Gstarts: from 1) wu eeevevevvovveve + plt-subplots() + Object-oriented way to create subplots + figsize=(wh) + Sot the size of the figure: + sharex=True > Share x-axis among plots + sharey=True > Share y-axis among plots Key Takeaways : V Subplots help to display multiple plots together. V Ik is easy to compare different data Y We can combine Line, bar, scatter, ete. in subplots VY Always use tight-layout() for a neat look: SHES HHHHHHHEHEHEHHHHEHHHHHEHEHEKHEHEHHEKHEHEHEEEEEEE EES MATPLOTLIB NOTES-9 |=“ 02 / 06 / 2024 17. Figure Size - plt figure ( figsize=()) We can change the size of the entire figure (width, height) using figsize parameter in [Link]() Example Cope : Ourtrur : ‘import matplottib. pyplat ax ple Small Figure (4, 3) Import numpy 08 np 10 # Date os x = [Link](0, [Link], 100) 3 y= npsin(a) ¥ 00 H Small figure * 0.5 plt. figure Cfigeize = (4, 3)) eA plt-plot(x, y, color="blue’) plt. title (' Small Figure (4, 3)") [Link] (*X') plt. ylabel( 'sin(x)") Large Figure (8, 5) oi 2 4 5 6 F x [Link](True, lineetyle='--", alpha+0.6) = silerye: fee 05 pit. figure (figsize- (8, 5)) 2 [Link](x, y, color="green') Me 0.0 ple litle Large Figure (8, 5)') = pltelabel ("x") 05 ple. ylabel(‘sin(z)') plt grid (True, Linestyle = alpha =0.6) 1.0 ple show () ood 2 3 4 5 6 F x EXpLANATION ee . Fi Nore : + plt. figure figsize> (width, height)) sets the size of the ; fees wane Use fgsize to make your plats + The first plot has size (4,3) — smaller mares auitshlaly fory presenti ens + The second plat has size (8,5) — bigger or reports 18. Save Froure - [Link]() We con save our plot as an image file using plt. savefig() Examee Cove : Ourpur (Display) : import matpletlipyplat aa pt Cuaiwi import nampy as np av # Data 2 + np-linspace (0, 40, 100) eee 08 Plot ple. plate, y. color! purpla', Unauidthe2) fUb. ble Cocina Wave") pit. stabel (*'X') Plt ylabel(“couCn)") Pit grid(Trua, Unestyle cos(x) 0.0 0.5 sValghe ore} # Sore the figure ll. avefig(" cosine [Link]', dpi 300, blow inches Light’) x # dpi > image quality plt show () EXPLANATION, + pit savafig([Link]') saver the current figure Common Fite FoRMars : = PNG = Good for presentations Chigh quality) + dpi 300 > sels igh renatin (dots per inch) + TPG > Good for eb (onallor ze) + Uboxinches «tight + removes extra white spaces + PDF > Best for documents (vector format) +The file t smsed im the current working directory + SVG > Scalable vector graphics (vector format) 49. Line Stytes, Cotors & Markers MATPLOTLIB NOTES -10 [Page No. : 10 te : 03 / 06 / 202% We con customize the appearance of lines using different line styles, colors ond markers Exampte Cope Ourpur : ‘port malplottib. pyplat as pit import numpy as np = npilinspace (0, 2#[Link], 100) yoo npasin(s) 322) YS npetan(e) / 3 it ecaled for better view yh > npeagrt (x) 1H Plot with different Line tylae, estore and markers pltiplat(e, yt, color="blue’, Linetyle =~ rrarkar='0°, label 'sin(z)") color rad”, Unaatyle + rrarker='s") label 'coe(z)") pitsplat Ce, y3, color = ‘green’, Unastyle =", rrartar='*', label» Yan(x)/3") [Link] Ce, yh, color="purple’, Linaatglas:', rmarker='d", label ="eqrt(2)") pltstitle( ‘Line Styles, Colors & Markee!) pltsalabel (°X valuas”) pits label CY values’) plbplot(a, y2, Line Styles, Colors & Markers pltlegend() chow lagen [Link](True, Unestyle '=-', alphas 0.6) pt show () Common Line [Link] Common Markers : "Solid line to! Circe Dashed line Se! Square Dach-dat Line Triangle Up Delted. line Triangle Down "D' Diamond iach cl acl aioe ‘et Star epee eae eee X (Cross), informative ond. oltractive. Plas : 20. MutripLe Pots (Suaptors) - ple. subplots( ) We can create muldiple plots in one figure using [Link]() Examete Cove Ourpur : import matplettib,pyplat as ple Multiple Plate using Subplats Inport py as" =» np-linapace(0, [Link], 100) ints) cos(z) gts npesnts) 20 10 2 = npccon(s) B= npstented / 3 or og ahs npeeqrtley > oo oo © Create igure nd. 252 aubplata fig, aes = pll-subplta(2, 2, fignise» (40, 7)) 08 5 sesL0, O)-plo(x, yy cols be’) “40 “to sexe0, OJ. at tile Sains)") tainas 7e a, xe[0, 0}. sot ylabel(°¥") ‘esl, OD. grid Tran, Lineatyla=--', alpha 0.6) tan(xy/3 etl) exe{0, 1].plot(s, yz, color="red) 40 a5 esl, 1] onttitle “con(a) a esC0, £1. grid( Troe, Lnenigle='—', alpha 0.6) os axes[t, O].plt(e, y3, clors‘green’) ae faes[t, O]-sst-title “tonCe)/3°) a oi crest, OJ. st ylabel°¥") x, rest, Ol. grid True, lineatyles’=-', alpha 0.6) : 05 enesLt, 1].plot6e, yo, cals! purple’) “40 me seal, [Link](“sqrt(e)'S eens o Gf 8 ¢ fect, £).geid(Trun, Uvertglas '--', alpha 0.6) 5 . fig-supitla('Malligla Plas using Subplata', fatsta 48) fig. tightclayout(rect=[0, 0, 1, 0.95]) # adjuct layout pbstheo Key TAKEAWAYS : Y plbcatplote Crows, necle) creates a grid of subplots Vanes is on array of Aves objects We can customise each subplot individually v fig tght-lnyout() automatically adjusts spacing Imeoatant_Nores + Tadic stark from 0. Example: aneal, 1] > frst rom, send. cola, + You can ute fgeze (with, height) to sat gure sine + Use uptitle() for main tle of the entre Figure Sllplatslere vay canal dee cnpuringirtpla dhe: mts w

You might also like