0% ont trouvé ce document utile (0 vote)
0 vues10 pages

data visualisation

Le document présente des notes sur la bibliothèque Python Matplotlib, utilisée pour la visualisation de données. Il couvre l'installation, la création de différents types de graphiques tels que les graphiques linéaires, les graphiques à barres et les graphiques en secteurs, ainsi que des fonctionnalités avancées comme les styles de ligne, les marqueurs et les légendes. Les exemples de code illustrent comment utiliser ces fonctionnalités pour créer des visualisations efficaces.

Transféré par

afubom99
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
0 vues10 pages

data visualisation

Le document présente des notes sur la bibliothèque Python Matplotlib, utilisée pour la visualisation de données. Il couvre l'installation, la création de différents types de graphiques tels que les graphiques linéaires, les graphiques à barres et les graphiques en secteurs, ainsi que des fonctionnalités avancées comme les styles de ligne, les marqueurs et les légendes. Les exemples de code illustrent comment utiliser ces fonctionnalités pour créer des visualisations efficaces.

Transféré par

afubom99
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF ou lisez en ligne sur Scribd
—_| TTT 7 OOOO SHEESH EKEEEEEEEEEEEEESE | MATPLOTLIB NOTES- 1 rs Pa 6 [202% I. Wxat Is MArpLoTus ? Moatplotlib is a powerful Python library used for data visualization. | Tt is used to create static, animated and interactive plots in Python. || Tt is the most popular Ubrary for plotting graphs in Python. | 2. INSTALLATION | We can instatt matplottib using pip. | | pip install matplotlib |. Importing MaTPLoTire import matplotlib. pyplot os plt | 4. First GRAPH The most commonly used module in matplotlib is pyplot. Note: Make sure you have Python installed in your system. pit is an alias which is commonly used. Let's create our first simple Une graph. Example Cope : Output: import matplotlib: pyplot as plt = Simple Line Graph, |_| x = [4,2,3,4,5] - ye [10, 20, 30, 40, 50] — | plt. plot (x,y) i _| ples show . | ° | EXPLANATION: ee | + x and y are the data points. |e ple. plot (x,y) is used to draw the line. + plt-show() is used to display the graph. | Key TAKEAWAYS : || + Matplattib is used for data visualization + pyplot module is used to create graphs. + pit. plot() is used to plot Line graphs. + Always use [Link]() to display the graph. Next Toptc —> Line Chart with Title, X label and Y label (Matplotlib Notes - 2) Poo adD eae EHH STH EHS HE HEHEHE KEHEHEEHEEKEHEEEEE MATPLOTLIB NOTES -2 5. Mutttpre Lines tn One GRAPH We can plot more than one line on the same graph to compare multiple data. sets. EXAMPLE Cope : Output : import matplotlib. pyplot as plt Multiple Lines Example x = (4,2,3,4,5) 6 = linet y= [10, 20, 30, 40, 50] so me Line 2 y2 = (50, 40, 30, 20, 10] plt. plot (x, y1, label » ‘Line 1") a” [Link] (x, y2, label = ‘Line 2") $30 plt. title(*Mulfiple Lines Example’) Ph [Link] ("X-azis') plt. ylabel (*Y- amis’) to [Link]() — # show Legend 5 [Link]( True) 1 2 3 4 5 [Link]() X-axis EXPLANATION : Tre: + We plotted two Lines (yi and y2) on the same graph. Legends are useful when we have multiple lines or plots to understand which Line represents + label is used to name the lines. + pltslegend() is used to show the legend (names of lines). + [Link](True) adds grid lines to the graph. 6. LINE CoLog We can change the color of lines in our plot ExAMPLE CODE : Output : import matplotlib. pyplot as ple Line Col Example x +(4,2,3,4,5] at y + (40, 20, 30, 40, 50) so [Link] (x,y, color = ‘green’, label » “Green Line’) 40 [Link] (x,y, color « ‘red’, Linestyle = '--', label = ‘Red Dashed Line’) ae [Link]( True) ple show 0) EXPLANATION = lor ter is used to set the color of the Line. coee cae sees Se ee ‘red’, ‘green’, ‘blue’, ‘black’, ‘orange’, . Linestyle = '+-' makes the line dashed. y oa oa , purple’, "brown k', “gray’ ete + We can use many color names or codes eevee eeseeeseedeeseuede eesesoeveeoeevoeeoeaeeoeee @ | (MATPLOTLIB NOTES-3 [i= | Date : 27 / 05 / 2024 | F Markers IN ‘Line Por | We can use markers to highlight each data point in the line. Markers make the graph more visible and attractive. | Exampue Cove : Output : || import matplottib. pyplot as plé je = (4,2,3,4,5] Line Plot with Markers 60 y = (10, 20, 30, 40, 50] 50 |] plt-plot (x,y, marker »‘o", color ='b’, 7 markersize © 8, markeredgecolor «'r', 3 markerfacecolor = ‘yellow’, linewidth =2) 3 30 [Link] (‘Line Plot with Markers’) ry [Link] ("X-axis') plt. ylabel ("Y -azxis") ple. grid (True) plt. show(), EXPLANATION ! + marker = 'o" uses civele marker on each point. + color = 'b! jets the line color to blue. ss > Circle + markersize controls the size of the marker, > Stor > Square "> Triangle Up +# 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. Example Cope : Output : ‘import matplattib. pyplot as plt 2 = [4,2,3,4,5) y= [10, 20, 30, 40, 50] Pit, ttle (“Line Styles Example’) ple slabel (°X- ple glabel C*Y pit. legend) pit. grid (True) pit. show() EXPLANATION : + inesigle contrats the sige of the Line 0 Nore [oe ts Solid Hine (default) 1 We can combine calor, marker dnd Line style . Dane es | together to make our plots mere effective i Dated: lina: and easy to understand. iy ets Dash-Dot line sa OOOOH HHEDKHAL SELLE TEESE EET ESOS MATPLOTLIB NOTES - 4 (9. Bar Cuaat (Verricar) ~ [Link]() We can create bar charts using [Link](). It is used to compare discrete categories. Examete Cove : Output : import matplottib. pyplot as plt Monthly Soles Bar Chart categories = ["Jan', ‘Feb’, "Mar’, ‘Apr’, ‘May "] & soles = [20, 35, 30, 45, 40] Es plt. bar (categories, sales, color = ‘skyblue', Bao edgecolor = ‘black’, width = 0.6) 8 plt. title ("Monthly Sales Bar Chart") oe plt. xlabel (Month) 42 [Link] (‘Sales (in 1000s)') 10 plt. grid axis = 'y', linestyle = ple. show () OK 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. HorrzonTaL Bar CHART - plt. barh() We can create horizontal bar chart using plt. bark () Exampue Cove : Oureur : import. matpletlib. pyplot as. plt Product Sales (Horizontal Ber Chart) products = {Laptop “Mobile', “Tablet, "Smartoateh' aay sales = (550, 750, 300, 450] plt-barh (products, sales, color» “lightgren’, ght enone 7 pl. title (“Product Sales (Horzental Bar Chart)" 2 pt label ("Salas (in units)") pl. ylabel ("Products") Laptop lt, grid (axis « x’, Linestyle + '--', alpha. = 0.7) —— lt show iho ato 300 wo #00 ew 100 a0 Sales (in units) EXPLANATION. + pltcbarh() is used to crete hovizmal bar chart. Conan anata? + catgeis are shou on he oasis and alt on the Sas ae sarang + TEU ase when category names are long s edgeclin) 5 Seth der caer of bh ; + wiatn + See width of bre Key TAKEAWAYS : + label), ylabel() + Sete ait lobes YY [Link]() > Vertical bar chart + ted 1 Sets the ttle of the chart. V [Link]() > Horizontal bar chart + gia ‘Adds grid lines. Y Both are useful for comparing categorical data. COCC HCOOH EEE ESE EEE EEE E LEE MATPLOTLIB NOTES -5 44. Pre CHart - [Link]() Page No.: 5 Date : 29 / 05 / 2024 We can create pie charts using [Link](). It is used to show part ~to-whole relationship ExampLe Cove : Output > import matplattib. pyplot at plt labels = [ ‘Python’, "Excel, “SQL', ‘Power BI’, “Other"] sizes = [35, 25, 20, 45, 5] colors = ['#4CAF5O', '#2196F3', ‘#FFCI07", "#9C27B0", '#FF5722') [Link], labels = labels, colors = colors, autopet = "%4.1f2%', startangle = 90, shadow = True, explode * (0,0, 0.1, 0, 0)) [Link] ("Skills Distribution") [Link] equal’) # Equal aspect ratio encures ‘Skills Distribution, circle shape pit. show () EXPLANATION : labels + Names shown for each slice + sizes + Values for each category + colors + Colors for the slices. Pie charts ave best used + autopct i Shows percentage on each slice « startangle —: Sets the starting angle of the pie chart # shadow Adds a shadows effect to the pie chart, + explode Separates. Cexplades) the slice (4). + axis (‘equal’) : Ensures pie chart is drawn os a circle (not oval) OTHER USEFUL OPTIONS IN Pre CHART 4. Wim Rencentase pit. pie (sizes, Labels + Labels, cutopet = "ht. Af") 2. Exrope Marans Ssices explode « (0.4, 0, 0.1, 0, 0.1) 3. Wdameut Mages Pt pie izes, labels» None, autape » "-1f8") 4, Dowwt Guser put pie (sizes, labels = labels, wedgeprope » (sith'0.4}, antopet = “[Link]') Other Poser BL sat Ercel 32 VY [Link]) is used to create pie charts VY autopet shows percentage of each slice. VY. startangle votates the pie chart Y explode is used to highlight important slice(s) Y axis Cequal’) keeps the pie chart in ciraular shape. When To use Pre CuasT ? # When you want to show parts of a. whole + When total number of categoriat it small (preferably less than 6 or 7). + Example : Market share, Budget allocation, Survey vesults, ete. Le ee ee MATPLOTLIB NOTES-6 = [=te=£ Date : 30/05 / 2024 12. Histogram - [Link]() We can create histogram to show the distribution of a continuous data. It groups the data into bins (ranges). ExamPte Coot import. matpletib. pyplat as plt Histogram of Render Data imgert wane ‘sain ‘# Generate some random data ‘[Link] (0) for reproducibility data + [Link](loe «50, scale « 10, sie « 1000) Ourrut : Plot his pltchist (date, bins + 15, color = ‘skyblue’, edgecolor + ‘black’ ) plttitle (Histogram of Random Data”) plt-slabel. ("Value") pi ylabel (* Frequency’) plt. grid Canis + "y", Uinestyle + '--', alpha = 0.7) plt-show() EXPLANATION. © data + Random data generated using normal. distribution fo bing = 45 : Dobe ts divided into 45 equal-width bine. © color : Fill color of the bars. = edgecolor : Border color of the bars fo grd(anis = 'y') : Adds horizontal grid lines 13. Scatter PLot - [Link]() We can create scatter plots to show relationship between two continuous variables Examere Cove : Output : import matplotiip. pyplot as pit Scatter Plot Example import mumpg as np 8 Sample data & + npearray((4, 2,3, 4 5,6, 7, 8,9, 40)) ym mpeorray (2s 8) 5,6) 7, 8, 7,9, 8) £47) ‘i Seatter plot plt-seatter Cx, , color « “purple’, marker =o", 5 « 80) pli title (Scatter Plot Example") pit. slobel ( Values") plt- ylabel CY Values’) pit. grid (Truc, Linestyle «°--", alpha = 0.6) pits show() EXPLANATION : Common MARKERS IN ScaTTER Puot : + [Link]() is used to create scatter plot. Gro (Gre + marker = ‘0’ sets circular markers ge gee + 5 = 80 controls the size of markers ‘st Square + Grid helps to read the values easily tat > Triangle Up MATPLOTLIB NOTES -7 14. Grip 1n_Piots - [Link]() Page No. : 7 Date : 31 / 05 / 2024 We can add grid lines to the plot to make it easier to read values Exampte Cove : Ourpur : import matplottib. pyplot as ple Line. Plot with Grid = (1.2, 3,4, 5, 6] = | y+ (19, 20, 25, 30, 35, 40] 40 # Plot line [Link] (x, y, marker = "0", color = 'teal', linewidth 2, label = 'Sales") as # Md. grid Bs pl. grid (True, linestyle = '=-', color» "gray", ns Uinewidth= 0.7) [Link]( Line Plot with Grid") pit-xlabel ("X-axis") pit. ylabel (‘Y-axis’) [Link]() : ‘ EXPLANATION ; + [Link](True) > Tums on the grid. + Linestyle = > Makes the grid dashed. + color ‘gray’ > Sets the grid line color. + linewidth=0.7 > Sets the thickness of grid lines 15. LeGenp tn Plots - ple. legend() We can add a legend to the plot to identify different lines, bars, etc. ExampLe Cove : Oureur : ‘import matplottib. pyplot as plt ‘Sales Comparison. w= (1,2, 3, 4, 5) © ji [i0, 18, 20, 28, 30) Sunt y2 (30, 25, 20, 45, 10] 2» [Link](z, yt, color = "blue", marker = Linewidthe2, label » “Product A’) plb plot (2, y2, color = "red", marker = Uinewidth=2, label» “Product 8°) Pll title Sales Comparison’) ple. alabel (X-axis) ple. label (* Sales") [Link]() show legend plt. show) EXPLANATION + + Label Used inde plot() te mame tach lin fs pltlegend() > Displage th lagend en the ple. gper af “oer lf Leceno Posrrron Options : at + Dafalt (bt postin) aype vight! + Top right + Tp Ue + Bao jt Kev Takeaways : Y pit gra Yo played) Adds gr Lines to the pit for better readability Shows a box that deerbes ins /plets in the graph YY These features make cur plats more professional and tary to understand MATPLOTLIB NOTES -8 wen Date : 01 / 06 / 2024 , 16. Supports - [Link]() We con create multiple plots in a single figure using subplots. Tk is very useful to compare different data side by side. Examee Cove : Ourpur : import [Link] as pit # Dota for plats == (42,3, 4,5) y= [10, 20, 30, 40, 50) y* (50, 40, 30, 20, 10) yb (5, 10, 15, 20, 25) # Greate subplots (2 rout, 2 columns) pltsubplt(2, 2,1) # Row 4, Cal 4 pit plat(s, yt, color ="blua’, marker='o") pl title ("Plat 1°) pit. slabel(“X") pit. ylabel€"Y") pllesubplot(2, 2,2) # Row 1, Col 2 pil pts, yt, color ‘red’, marker="s') pil title (“Plot 2") pl label") pit glabel"Y") pit. subplot(2, 2,3) Row 2, Colt Blt. plot, ys, color =‘gresn’, markar="*") pit. ttle ("Plot 3°) pit. xlabel €'X") pit ylabel'Y") pltasubplot (2, 2,4) Row 2, Gal 2 pit bata, ys, calor + orange’) pit. ttle ("Plot 4 (Bar Chart") pit. slabel ('X") pit. ylabel('Y") ple. subplot(nrows, ncols, index) + rows > Number of rous + reals + Number of columns + index + Position of the plot + pb. subplot(2, 2,1) means 2 rous, 2 columns and this is the 1 plot. + We can add different types of plots in each subplot. + pit. tight-layout() adjusts spacing between flats automatically CCC HEOHRECHOHCOHOHSHHHHHHHHKHHEHHHKHHHHHHKEHHE Orwer UseruL Functions : Key Takeaways = + pltsubplote() + Object-oriented way to Subplots help to display multiple plots together. create subplots Tk is cosy to compare different data. + figtizerCo, h) + Set the size of the figure We can combine Line, bar, scatter, ete. in + tharezsTrue + Share oasis among plots subplots + sharey=Trut + Share y-axis among plots, Aare ok yh Te OR ee eee eee eee eee ERE eT MATPLOTLIB NOTES-9 [a=*=2——] Date : 02 / 06 / 202 17. Fraure Size - plt figure (figsize+()) We can change the size of the entire figure (width, height) using figsize parameter in [Link](). Exameve Cove : Output : import matplottib. pyplat ax pt Small Figure C4, 3) import rumpy as np 10 # Date os + [Link](O, [Link], 100) 2 yt mpsin() |Z ost # Small figure * Los plt figure figsize = (4, 3) aS plt plata, y, color» “blue') pll. title (Small Figure (%, 3)') ple alabel (°X°) ptt. glabel(sin(z)') Large Figure (8, 5) [Link](True, Linestyle+'=-', alphas0.6) Lo # Loge figure as ple figure figeizes(8, 5)) is [Link](z, y, color ‘green') S00 pit title C Large Figure (8, 5)") $ pltalabel °°) 05 pit. glabel( ‘sin (z)') PUL. grid (True, linestyle '--', alpha+0.6) “1.0 Bede) o i 2 3 8 § 6 F EXPLANATION + ple. figure (figsizes (width, haight)) sets the size of the figure in inches. + The first plot has size (4,3) > smaller +The second plot has size (B, 5) > bigger Note : Use figsize to make your plate more suitable for presentations or reports. 18. Save_Fiaure - [Link]() We can save our plot as an image file using plt-sovefig(). Exampte Cove : Oureur (Display) : Inport matplotibpyplat ox pit Cosine, Wore import numpy at np “8 # Date x = np-linspace(0, 40, 100) ape a OS calor «purple, Unewidthe2) 300 pine Wave’) #. x) ptt. glabel( “eos (z)") os Pb ged True, Unesigle =~", alphan0,6) “te 1 Save the figure . 6 8 10 ptt. savefig (“cosine [Link]’, dpi 300, [Link] tight") a a § x # apt image quality pts show() File coved as oe ) uatecmeaig Common Fire FoRMATs : + plt-savefig( filename png’) see the caret figure mes Ge : % high quality) + dpi 300 -> sats Nigh reselain (dote per inch) me de + Mncinahes © "ight" -+ removes ent ohite spaces. |) PDF Bt for deamuts (ator format) +The file is smd in the carent wihing dialog + SVG + Selale vector graphics (vitr format) Page No. : 10 Date : 03 / 06 / 2024 | MATPLOTLIB NOTES -10 19. Line Sryues, Couors & Markers We can customize the appearance of lines using different line styles, colors ond markers. Exampte Cove : import [Link] as ple import mumpy as np 2 + npilinspace(0, [Link], 100) gt npsin(a) g2 = npecor(a) gh nptane) / 3 ge apeaget(2) © Plt with diferent line alas, colors and markers PL plate, yh, color ="bl’, Lnatye + water #6, labeh in) PbaplaGe, ya, color "red", Uinaatyle =, rarer #6") beh eon (3) tiple, y8, calor "green’, Unaatgs'=", markers", lads "tan()/3°) PbipletCe, yb, clr purple’, Unestyles marker ='d', labels aqrt(z)") HL tile “Line Styles, Clore Maskars") HE alae (°% vale) HE glabel(*Y values") Oureur : Une Styles, Colors & Markers We azalad for better view plblagend() show lagen plb-gridTrua, Unestyle='-', alpha 0.6) plbsthow Common Line Styues : Common Manxens You con mix and match ‘en Ci 8 Beds ( ye es ee Deon 7 Sore ws togeup [im xen Ny GSR I eRe 5 20. Murtipte Piots (SuspLots) - [Link]( ) We can create multiple plots in one figure using [Link]() Examece Cope : Oureut : import malpatih-pgpiot a= ple path aang = aplinpace(0, 2+[Link], 100) gee fa pene $3 nptene) / 3 a a oe paytced 1 Creala figure and 202 sublets Figs cous + ptt sbplate(2, 2, figeaa (30, 72) asasl0, OD. pate, yy cle o"Ba") 10. ‘SLO, O) atte sine)" o fs 6 or 8 6 Salo, Of atiylab YD ‘Sesf 003. gridl Tron, Linatyte ==". alpha 0.6) Apis, ya, colar ered") 10: as eulo, 1} net tide (ears)? ~ Sa(OL 1D grdC Tran, Unesigle "=, olpha= 0.6) os. ese, OD plata, 92, eaters 'graen) as LL, 0} net tile tnd) 10 ESIC of toys) SICH! oD grdt True, Unetgle =, alpha 0.6) saat, AD plate, hy eater» purple") +19. 00 eee 1) nettle aged oa 4 6 of 8 6 eC AD. gridC Tron, Unentgle >", alpha 0.6) e 9 ‘fig-esptla Maps Pt waing Subplts, fontaine 18) Figsighl-lngetCract-[0, 0, 1, 0.95]) # adjuat Une Hshoo Multiple Plots using Subplote sint) 10. 40 cesl2) > 90. 00 28 0s eulo, 8 oa Key TAKEAWAYS + Y pltsmbpltalnro, mele) crenata grid of spt Iewonranr_ Nores : Indies sort frm 0. Example: eneal, 1] + fest von, ted cla, Sen earn of faa bj Yo We can catomin th ubplat individally YY fgitightalngost() automatically adjate apacig. Yo cam ae fg Cot, Maight) Lo a figure sae + Ue mptitle() for main tithe of Ua entire Figur + Sabpate are vary util for comparing vulipla dte sae wy

Vous aimerez peut-être aussi