You are on page 1of 44
Unit - 5 DATA VISUALIZATION Importing Matplotlib - Line plots — Scatter plots — visualizing errors —- density and contour plots — Histograms — legends — colors — subplots - text and annotation — customization — three dimensional plotting - Geographic Data with Basemap - Visualization with Seaborn. 5.1 IMPORTING MATPLOTLIB Data visualization is of greater significance in data science. It is used for many tasks such as exploratory data analysis, model evaluation, storytelling, and so on. A well-designed cata visualization can be much more informative than plain numbers. The two main components of data visualizations are what they represent and how it is represented. What they represent is the data to be visualized. The “how” component is just as important as the data. The visualization technique can make a big difference. Matplotlib is a multiplatform data visualization library built on NumPy arrays, and designed to work with the broader SciPy stack. It was conceived by John Hunter _ in 2002, originally as a patch to [Python for enabling interactive MATLAB-style plotting via gnuplot from the IPython command line. Important features of Matplotlib © Ability to work well with many operating systems and graphics back-ends. * Supports dozens of back-ends and output types. * Everything-to-everyone approach has been the great strengths of Matplotlib. * Has a large userbase and an active developer base © Matplotlib’s powerful tools have become ubiquity within the scientific Python world. Importing matplotlib In[1]: import marplotlib as mpl import matplotlib.pyplot as plt | Setting Styles The plt.style directive is used to choose appropriate aestheti The classic style is set, which ensures that the plots use the cl: les for the figures. ic Matplotlib style: eh co teers Ce re ee In[2}: pl 5.1.1. Plotting from a script a script, then the function pitshow() starts an figure objects. and opens one or More inte Run this script from the command-line prompt, which will result in a window opening with the figure displayed: ) command must interact with the system's interactive graphic 5.1.2 Plotting from an IPython shell It can be very convenient to use Mat interactively within an IPython stel iibmode. To enable command after startingipython: this mode, you can use the %matpl In [12 Smatplotib Using matplotlib backend: TkAge Plot command will cause a figure window to open. 2 8 10 update the plot. Some changes (such as mod to force Hib mode is not required 5.1.3 Plotting from an IPython notebook The [Python notebook is a browser at oi ‘based interactive data analysis 100! be oak combine narrative, code, graphics, HTML. ete executable document. Plotig interactively within ay 4 te do with the Sematplotib command, and works in Python notebook canbe i ilar way to the 1Python sh! Option of embedding grphics direciy im the fPython’ noted notebook: taaneniont a «© ematplotlib i oa notebook : Will lead to interactive plots embedded within the ‘Afier you run this command (it needs to be done only once per kernel any cell within the notebook that creates a plot will embed a PNG imag resulting graphic. 41: import numpy as np 05 aa © sO Fig. 51 Example for Basie plotting 5.14 Saving Figures to File ing Figure lows to save fig avefig() command. sures in a wide variety of formats. Figures can be For example, to save the previous figure as a The file called sine_cos.pg isin the eureat working SON: To display the contents of this fle: Srom [Python.display import Image Foundations of Data g pee Se of the given filename, using the following ‘pet's "PGF code for LaTeX ‘pugs ‘Portable Nenwork Graphics igged Image File Format’ vif'> Tagged Image File Format’) 5.1.5 Two Interfaces of Matplotiib ‘+ MATLAB style state-based interface ¢ object-oriented interface sa Visualization aa eee Nie Me ee oN 515eh MATLAB-style Interface ly written as a Python alternative for MATLAB users. the MATI le tools are c Tis familiar 10 MATLAB users" ® PYPlat sface. The following ‘and set current axis (rows, columns, panel nunber) nd panel and set current axis att = Ere © This interface is stateful: © Keeps track of the “current” figure and axes, hese can be obtained using the plt.gef() (get current figure) current axes) ‘ ind convenient for simple plots 1g the second pane! cannot * Reference to * Adding something to the first panel after creatin be done. 5.1.5.2 Object-oriented interface © The object-oriented interface is 2 Prova more conto over the EWE ailable for more complicated situations and t figure and axes objects * Plotting functions are methous of Foundations of Di ET ture the code more ye code blocks. Fig, 54. sin and c0s function 5.2 LINE PLOTS ‘The pyplot, a sublibrary of matplotib, is a coll creating a variety of charts, Line Plots data X and Y on a different axi ‘are used to repres * Import Matploti.pyplot library for ploting functions. * Import the Numpy library as_per requirement, + Define data values x and y. Examples of a line est of all plots rt visualization of single function y = f © mas lt np Plots, a figure and an axes is created. In theit simplest form, figure and axes can be created as follows. 1 fie = Plesiguret) ax = plt.axes() 19 oa oa 02 05 Of os 10 Fig. $5 An empty gridded axes Use the ax.plot function to plot the data ‘nll: fig = plefiguret) ax = pliaxes() x = npllinspace(0, 10, 1000) axplot(s, np.sin(s)): 19 yo 8p = | oof -— oy moet : “0 19 =e ‘ Fig, 56 Simple sinusold i i Rs oe eas call the plot function multiple time, To create a single figure with multiple lines, In(}:pluplott, np.sin)) M(x. mp.costx) 19) i 3 os 3 00 ad ves data Fig, £8 Multiple plots sof NS 521 Setting Line Colours and Styles ee a oH ot() function takes additional arguments to specify line colors and styles. r rreatiog romiigha mes just the col is used, which accepts ing argument fon the same axis representing virtually any imaginable color. The color can be specified in a variety import matplotibpyplot as plt of ways: import numpy as np In: eel "Oj, color="blue") F specify color by name 7" : 21), color='s') # short color code (rgbemsk) 4 first plot with X and ¥ data 2), color="0.75°) # Grayscale berween O and 1 pleplots, yp 13, color='#FFDD4') —# Hex code (RRGGBB from 00 to FF) al =[2, 4.6, 8] 24), eolor=(1.0,020. # RGB tuple vt =13, 5.7.91 = 5), color='charre all HTME color names supported # second plot with x1 and yt data pleplonst, y1. pli.xlabel("X-axis 50, Foundations of Data Scien, style can be adjusted using the Hinestyle keyword: Style or gg 0 z 7 6 7 Fig, 5.10 Example of various tine styles i ea ee Ss coal ined into a single non-keywor 1 # solid green M dashed cyan ‘pata Visualization a plplot(s, x + 2, pliplot(x, x + 3, to Fig. $.11 Controlling colors and styles with the shorthand syatas. 5.2.3 Setting the Axes Limits of plots by adjusting the axis W191: ple.plon Ibo}: p Foundations of Data Sti, Bienes | aed a ee a 10 05 00] os 10 © 7 3 7 z 0 Fig. $.13 Reversing the y-axis ‘The pltaxis() method allows to set the x and y limits with a single call, by passing a list which specifies (xmin, xmax, ymin, ymax]: Inf}: pleplot(s, pltaxist(- ISD; DEST PSRs a aaa Fig, 5.14 Setting the axis limits with The plt.axis() method allows to around the current plot: 40 things like automatically tighten the bound ‘pata Visualization The plt.axis()allows higher-I ratio so that on screen, one unit in x is equ Inf: pleplot(x, plas ‘equal’: 0 the output resolution Fig. 5.16 Am equal layout with nit mated fo te ove solu 5.2.4 Labeling Plots Labeling of plots with as below. The pos to the ¢ legends done ets, and simple legends can be lebrlgyle of these labels can be adjusted Asie Cuve 10 syntax K ‘The syntax for scatter() method is given below: 1 matplotlib.pyplotscaterts_axis data, y axis data, s=None, —_e=None. | marker=None, cmap=None, vmin=None, ymax=None, alpha=None, linewidths=None, Zoo 1 - tedgecolors=None) a Where, 05 © x.axis_data- An array containing x-axis data | © y-axis_data- An array containing y-axis data ey 8 6 @ 10 's- marker size (can be scalar or array of size equal to size of x or y) ‘* c color of sequence of colors for markers © marker- marker style © emap- cmap name © linewidths- width of marker border © edgecolor- marker border color — sar © alpha- blending value, between 0 (transparent) and 1 (opaque) 608 (0) 12,9. 6) 7, 94, 78,77, 85, 86) FieS.8 Plo legend 5.3 SCATTER PLOTS TTT ean srg, 5.19 Seater plot Foundations of Data Scie, ay pale ee Inf}: Smaplnlib inline import matplotib pyplt as pit pli-style.usel seaborn-whitegrid’) ‘import numpy as "9 5.3.1 Scatter Plots with pit.plot pitplovax plot to produce fine plots. It tumsout that this same function cy produce watter plots as well. : Inf2): x = nplinspacel0, 10, 30) y= mpsints) pleglottx, y, “0°, color="black'): i character that the ty of symbol used for the plotting. Symbols a ahd a an beat ni ae ‘marker (0), black (k) so o 2 ‘ 7 + Fig. £22 Customizing line aod poi numbers 53.2 Scatter Plots with pit.scatter create scatter plots.The main difference bbe used to create scatter plots where .. face color, edge color, ete.) can be Foundations of Data s, Fig. 5.23 Simple seatter plot Random scatter plot with points of many colors and sizes is shown below, order to better see the overlapping results, alpha keyword is used to adj transparency level: In}: mg. = np.random RandomState(9) x = mg.randn( 100) y = mg-randn( 100) ‘colors = rmg.randl(100) 1000 * rng. rand 100) Geter ae ‘nd transparency in scatter points mat or mapped to a color scale’ (shown hereby 'S given in pixels. in this way, the cO a Visualization a aod size of points can be used to fp illustrate multidimensional data lasses of colormaps in sca categories based on tt 1, Sequenti used fo represent information which does not hav or relationships, For instance, the Iris data from oneof three types of flowers whose size of I: from sklearn data iris = load ir kit-Leam is usedin which ea petals and sepals are c, bas | 20 i; ie to 8s § zo 5s 60 6 ee ‘Sepa aoa Fig, £25. Using pot properties (0 fig. = plifigurevfigsize=(8, 8)) im = Basemap(project resolution=None, 5, alpha=0.5) to (x, y) for plowing % y = m(-1223, 47.6) pit plots, y, ‘ok’, markers plttext(x, y, ' Seattle’, fon Fi, S72 Ploting dats and labels on the o map 141 Map Projections 561 lons = mdrawmeridians(np.linspace(-180, 180. 13)) # keys contain the plt.Line2D instances lat tines = chatin(*(tupl1 (0) for sup in la all_lines = chain(lat_lines, lon_tines) 4 ole through these lines and set the desired sole” sipha=0.3, color="w") S114.1.1 Cylindrical projections ap projections are cyli and longitude are map . indrical projections, in whic Ce ped to horizontal and vertical ines, of constant latitude respectively. ; © This type of mapping represen quaorial regions quite well, but resus in extreme distortions near the POIs varies beween different csindrical rokeerSr tude lines varies PoE and different distortion near the ‘©The spacing of acing erent conservation PrOP=T leading to diffe Poles. * Depending on application ot Gireeton area, cstance, S406 different map features (© (ae ee tions) can be defined. ther considerat neurctigaernit, 62 cierto) Foundations of Dat 1a Visualization Ua Sciongy fF aa Vavalzaton ——— 5.63 Fig, 5.74 The Molleweide projection 5.14.13 Perspective projections © Perspective proj are position. Orthographic proj globe as seen from a viewer ew specify the latitude (lat) and ths oko ea, tie ft comer (llemt) and upper-right comer (urct itional arguments to Basemap f the lower map, in units of degn i the gnomonic projection © Other _perspective-based projection: le ca (projections”gnom’) and steeographic projection (projecton="sere') 1 the most useful for showing small portions of the map © These are ofter 514..4 Orthographic projection The Mollweide projection (proj elliptical ares. Its constructed so there are distorions near the true area ) defines. all meridians #8 0 preserve area across the map: though . the area of small patches reflects tH 0=50, lon.0=0) draw _map(m: ‘ortho’, resolution= None, © Other pseudo-cylindrical_ proj ‘and Robinson (projection=" the sinusoidal (projection="si & Projections eo 14.1.5 Conic projections is thea unroll ‘onto a single cone and is thea unrolled. ae: but regions far from the focus * Conic projection project = moll’, resolution =N ‘This can lead to very ee ee point of the cone may Lambert Confort a cone arranged Basemap by decreasing between ! ter NEMA eFC 10 the oy the desired. map, itude (lat_0) a" 584 Foundations of Data Scions ae Foumntatons ot: Data Sctancy * Other useful conic projections are the equidistant conic projection (projection="eqdc’) and the Albers equal-area projection (projection="aea’) © Conic projections, like perspective projections, are good choices for representing small to medium patches of the globe. In [ I: fig = plefiguretfigs Fig. $75 The Albers equal-area projection 5.14.2 Drawing @ Map Background ‘The Basemap package contains functions for drawin rawing borders of physical features Bike continents, oceans, lakes, and rivers, as well as poliat Boundaries The following ae some of the available drawing functions using Python’ help features: Physical boundaries and bodies of water * drawcoastines() : Draw continental coastlines + drawismask() : Draw a mask DTECng images On one or he nas” MOY ind sea, for use ith + deawmapboundary() : Draw oceans . '¢ map boundary, including the fill color fo * deanrivers0: Draw rivers on the map os visualization fe a ene poitical boundaries + draw counties): Draw country boundaries + drawstates): Draw US state boundaries + drawcounties(): Draw US county boundaries Map features + drawgreatcircle() : Draw a great circle between two points + drawparallels(): Draw lines of constant latitude + drawmeridians(): Draw lines of constant longitude © drawmapscale(): Draw a linear scale on the map Whole-globe images * bluemarble() : Project NASA’s blue marble image onto the map * shadedrelief(): Project a shaded relief image onto the map * etopo(): Draw an etopo relief image onto the map * Warpimage(): Project, e effect of the resolution sanghtimple of drawing landlsea ha sf Sealand. U's located a ‘ameter. Create both a low- and high- meters shown in Fig. 38N,628W and = map of eo et, 02573, fon 082 20000, resobution= eee ms sora #ODEEFF fake coer mfillcontinense{color="#FFODCC peo "™drewmapboundary(il_color="#DDEE drawcoasttinest) oe “11h set sitet resolsion= 101 fm Foundations of see Ft tate ty Fig. $76 Map boundaries at low and high resolution ‘The low level resolution would work just fine for a global view, and would be ‘mech faster than loading the high-resolution border data for the entire globe. 5.143 Plotting Data on Maps Using Basemap tool kit we can ov background. For simple plotting and text, an est the Basemap insance to project latitude and ‘soordinases for plotting with pl, Basemap function: similar to their standard Matplo it additions jose ae Matplotlib pit with an Set to True to pass raw latitudes and longitudes !° ‘She method, rather than Projected (x, ¥) coordinates, Some of these map-specific methods are: Setowriveonioesf) : Draw contour lines or filled contours + imsbowt): Draw an image * Pealertipcolonmesh(): Draw a pre Phot): Draw fines andor markers seater): Draw points with markers * quiver): Draw vectors, * abst): Draw wind: barbs, + Arawpreacitcle): Draw a great circe Example: Surface Temperature Duty soul 0 bap Matas: nasa gr pagsemnyy, # Spuncip,gistenip 250 ne: 32 ‘udocolor plot for irregular/regular mes Me the GIS 250 temperature da? MMP250 ne ye ata Visualization SS ah a eee ‘The data comes in NetCDF format, which can be read in Python by the netCDF4 library $ conda install netcdjs ‘romnerCDF import Dataset Contains many global temperature readings on a variety of dates; Select the index of the date we're interested in—in this case, January 15, 2014; nik fromnetCDF#import date2indes fromdatetimeimport datetime timeindex = date2index(datet 15), data variables{ time’ jp ‘empanomaly'Jftimeindes} : Use the pcolormesh() method to draw a color mesh of tr ata, cole on America, and use shaded relief map ia the bockground. Divegsat colony chosen, which has a neural color at 220 and (wo commie es Positive values. Also draw the coastlines over the colors for reference: colution='c*, width=8B6, heigh BEB tot OotS, tatlon= True, oma RAB, Foundations of Data Sciency pe nan ee 5 porn versus Matplotlib se Example: Simple random-walk plot in Matploui, Using its classic plot formatting spd colOUts. " ‘ow create some random walk # Create some data mg = np.random.RandomState(0) x = mpllinspace(0, 10, 500) Fig. 5.77. The temperature anomaly in January 2014 5.15 VISUALIZATION WITH SEABORN a3}: Matplotib has proven to be an extremely useful and popular vis But there are several limitations in Matplotlib: * Prior to version 2.0, Matpi S defaults are not the best choices. It was based off of MATLAB circa 1 1999, and this often shows, ‘* -Matplotlib’s API is relatively low level * Doing sophisticated statistical vi code. ization requires a lot of boi plate + Matplotiib predated Pandas by more than a decad designed for use with Pandas DataFrames, TF Saat one ees the DataFrame labels ete sk plot Fg. $74 Data ta Matpotib™® wot anti the came information. te ered ting FORME. ows la an wa get eve sele ete a can bee alin The limitations of Matplotib are overcome by using. Seabom, Seabor provides an API plot style and color defaul plot types, and integrates that offers, various cho funetions for common Provided by Pandas. DataFrames Matplotlib’s 10 produce vastly Maiplotib team has recently added the 9 method. Pandas data more seamlessly. Seaborn ix an oy Is and is starting to handle 'Y useful add-on for Matp! eae Sin Ss te ol aes ae Foundations of Data Seine, By convention, Seabor is imported #5 5 saborn as sms the same ro lines 0 before Fig, 579 Data in Seaborn's default style 5.15.1 Exploring Seaborn Plots ‘The main idea of Seabom is that i variety of plot types useful for sta model fitting it provides high-level commands to create # tistical data exploration, and even some statistical Note that all of the following could be d (this is, in fact, what Seabom ‘more convenient. a lone using raw Matplotlib commands der the hood), but the Seabomn ABI is must 5.15.2 Histograms, KDE, and d a ee techniques. Kernel Density Estimation (KD! ane of the techniques used (0 smooth a histogram. seaborn.histplot() is use to plot | histogram with a density plot | Sys | cabomisplondata, x, y, hue, tut, bins, binwidt, discrete, kde, log_scale) | where, | 5 datas input data nthe form of Detaframe or Numpy array ow mal): key of the data 10 be positioned on the x and y axes 1al): semantic data key which is mapped to determine the color of plot elements |: count, frequency, density or probability axes with the plot drawn on it. Return: This method returns the matplo | # import necessary libraries | imponseaborn as sns ‘mporimumpy as np importpandas as pd dataset of random numbers “Numerical Variable") "Shistplot(data =num_var, kde =Trte) eee i “There are other parameters that can be passed to jointplot for a hexagonayy based his ta, kind="hex') lationships in a dataset. This function will create a grid of ach numeric variable in data share * The diagonal plots are treated differently: a univariate distribution plot is drawn to show the marginal distribution of the data in each column. It is also possible to show a subset of variables or plot different variables on the rows and columns. This is a high-level interface for PairGrid intended to make it easy tributions in a dataset, pairplot() function ) combination of variabl ix of plots and the diagonal plots are the univariate plots. seabor pairplo data, \\Mkwargs ) Seabor pairplot uses below in form of table: is used. This shows the relationship for as a mi ‘many arguments as input, main of which are described Example: Iris datasct- measurements of lh: = sms load_dataset"iris) Petals and sepals of three iris species ae “pel width [peta Tength | petal width ; Ds it i 457 30 a 7 a7 32 we 5 a6 3 i 3 50 36 ae Visualizing the muidmemint lana a In [ J: sns-pairpl iris, hue "species, scena 5 pata Visualization 5.75 n four variables Fig. 5.84. A pair plot showing the relationships twee 5.15.4 Faceted histograms abe aswell a He or one vile ox wel on ere dase sg Jons = row, col. and hue. imens sak OF up to three dit ng array of axes: think of ith els m pondence wil eel ‘where different levels are ong # ‘A FacetGrid can be draw The first ewo have obvious comesPont the hue variable as a third dimen Plotted with different colors sm Fate ot Data Sng | visualization pap Vsuolzatog 82 © FacetGrid object takes a dataframe as input and the that will form the row, column, or hue dit The variables shoul! be categorical and the data at each level of the vari will be used for a facet along that axis “4 - * Sometimes the best way t0 view data is via histograms of subsets Seaborn’s FacetGnd 20 Example: Consider some data that shows the amount that rest in tips ca. various indicator data: see ate ° 16 oa 8 j » | Fig. SAS Faceted hitograme $185 Factor plots day time Factor plots allows to visualize the distribution of a parameter within bins defined Sun | Dinner size 2 by any other parameter: Sun Dinner [3 Sun | Dinner 3 Sun | Dinner 2 | 4 Sun | Dinner maple his, tip") lt shows) cween different the joint distrburiva between i Moe ds 2 pL Of THO $15.6 Joint distributions das Pairplot sns.jointplot is lasets, along with the assoc! n variables with bivanate and unvarae & used 10 show jared marginal 4 Foundations of Data Scione, SUB ee So ay terface to the JointGrid class, with sever y lightweight wrapper; if you neey total_bit Hig. 6.87 Joint distribution plot The joint plot can even do some automatic ke it imatic id oe "mel density estimation an Inf I: sns.jointplos( "tora. "tip", data=tps, kind='reg'); te Pearson = 068: p= 670-24 . ‘ a 2 ° 4 310 0 10 20 30 49 so ‘tabi ° Fla, $88 Joint distribution plot with g regression fi it yualization pe pit aoe 5.15.7 Bar plots © Barplot is used to aggregate the categorical data according to some methods and by def the mean «It is used to visualize the group by action, © To use this plot we choose « categorical column for the x-axis and a numerical column for the y-axis, it creates a plot taking 2 mean per categorical column. + Time series can be plotted using sns.factorplot. Example: Planets data that we first saw in Aggregation and Grouping: In [ J: planets = sns.load_datasei'planets’) planets.head{) Out method Inumber| orbital_period | mass | distance year | 0 |Radial Velocity I 269.300 7.10 77.40 2006 | 1 [Radial Velocity | 1 874.774 2a | 5695 | 2008 | 2 |Radial Velocity 1 763.000 260 | 19.84 | zit | 3 |Radial Velocity 1 326.030 1940 | 11062 | 2007 4 {Radial Velocity 1 516.220 oso | 11947 | 2009 "Uh: with sns.ares_stylet white’): 2 kind = 8 = snsfactorplo("year”, data=planets.dspect=2.k Se xticklabels(step=5) “count”, color="steelblue') sao _—tatins of Data Seange ay visualization SE Features Matploalib I aa ie uses thy eaatively complex] uses comparat ely simple as S ively simpl symax which i ce . aes bargraph-[and understand Esp wns Pyplot : : es (X_axis, | Syntax for ‘bargraph- seabor.barplot(x_axis, y-axis) Dealing Multiple Figures creation of each figure. It may lead to (OOM) out of memory 2012 Fig. 5.89 A histogram as a special case of a factor plot We can lea more by looking at the ke y looking ‘method of discovery of each of these } [visualization In [ I: with sns.axes_style("white’): eaters data visualization Pyplot provides similar features land syntax as in MATLAB. [Seaborn is more comfortable in handling Pandas data frames. It uses basic sets of methods 10 [provide graphics in python Pliability Matplouib is a _highly/Seaborn avoids overlapping of| customized and robust plots with the help of its defaut [themes Data Frames and|Matplotlib works el Arrays ‘with data frames and array teats figures and axes as objects, Use Cases lib plots various graphs|Seabom is the extended version ae Pate ‘and Numpy fof Matplodib which uses : Maiplotiib along with Numpy) and Pandas for plotting graphs | Features Matplotlib Functionality “It is uilized for making basic Braphs. Datasets are visual ea ie hey visualised| and plots for data, si ation. It helps it compiling whole data it es . It also provi Cistribution of data. ienificance of Data visualisation. | greater significance in data ‘model evaluation, story formative pe Ronen ot atn tea, 2. List the important features of Matploti. Ability to work well with many operating. ‘Supports many of back-ends and output . tems and graphics back-ends © Everything-to-everyone approach has been the great strengths of Matploti, large user base and an active developer base powerful tools have become ubiquity within the scien pleploas, psn pitplons, mp.cosix), pata Visualization oe ee 4, List the interfaces supported by Maipotb Two Interfaces of Matploti: (a) MATLAB-style state-based interface : Python alternative for MATLAB users This interface is stateful: Keeps track of the “current” figure and axes. Stateful interface is fast and convenient for simple plots Object-oriented interface * The object-oriented interface is available for more complicated provides more control over the figure. © Object-oriented interface are more readable and exp! 6 Write code to plot sine wave using line plot. Line Plots are used to represent the relation between two data X and Y on a different axis. Use the ax.plot function to plot the data. I fig = plefiguret) a = pluarest) x = np.inspace(0, 10, 1000) axplot(x, np-sin(x)): % How can it colors for line plot. you set differen ify line colors and styles. ‘The plt.plot() function takes additional arguments 10 specify To ais Se oy color Keyword is used, which accepts a string ‘ror "presenting virtually any imaginable color. The color ean be specif af Ways: 0}, color="blue’) # specify color by es " color code (rebem 1), color=' # short J clor075),# Gra Breen Dane vopeneFDDH') # Hes code (RRGGBB Som al Phiplons, mp.sin(x - Pltplonx, np.sin(x - Pleplons, np.sinix Foundations of Data Science Gime is a eee 8. List the line styles supported by pyplot. a ‘The line style can be set using the linestyle keyword: Style or. id’ (default) dotted” ‘dashed’ “dashdot’ *None’ or” 9. List the applications of Line plot. A line plot is used to display a trend in data. It is used to express a relationship between two variables. Ex: To see the performance of a company in the daily stock market for a year. 10. What is scatterplot? 11, Write the syntax of scatter() method. maiplotlb pyplotscatter(x_axis data, ‘marker=None, cmap=None, vmin=None, vr Y-axis data, — s=None, _e=Nont. rmas=N =Novie, linewidths=None. ote em one, alpha=Novie, linewidths =Nowe where, X.anisdata- An array containing sais deta yuanis data- An array containing y-axis 5 marker size (can be scalar oF array o €- color of sequence of colors for markers rmarker- marker syle cemap- cmap’ nome linewidths- width of marker border ‘edgecolor- marker border color Ape: bending vale, been 0 rane and | pau ie equal to size of x or y) visualization Se mnt ese ge | Bae 1p, Enumerate the classes of colormaps in scanerpot « Sequenti used for representing information that has ordering. + Diverging: used when the information being value, such as topography or when the data deviates © Cyclic: used for values that wrap angl hhas a critical middle around zero, u around at the endpoints, such as phase wind direction, or time of day + Qualitative: used to represent information which does not have ordering or relationships 13, What is the significance of Error bar. Error bars indicate the estimated error or uncertainty to show how precise a suremenVanalysis/model. Error bars function used as graphical enhancement that alizes the variability of the plotted data on a Cartesian graph. 14, What is contour plot? Write its usage. i way to show 2 Contour plots (sometimes called Level Plots) are a way to 3 three-dimensional surface on a two-dimensional plane. It graphs two predictor variables XY on the y-axis and a response variable Z as contours. These contours are sometimes called z-slices or iso-response values. 1S. What is a histogram? the umber A histogram is a graph showing fete ne aoa useful in Lianne on hgh ert NE ng a dataset. ®e line, once the normal boiler "6. Define Kernel density estimation. iE enh Sommon method of evauang me ake peat ity catia, |. KDE is a Way imple KDE ir wpaly timation (DE ooh futon. ie eae that slides the knob ei, osu to obta ior KDE has 3a ney tal between, oe ee ness. gaussian kee a nN detail. an “ “Moothing length for the input Jatt dimensions is. kemel ‘multiple ‘od aid se anion of Bat Sing 17, Mention the significance of subplots. Itis a group igure, These subplots. might 18, Comment on text transforms. Anchoring the text to a position on the axes or figure, independent of can be done by modifying the transform. There are three predefined transform: mransform=fig.transFigure); 19. List the ways to customize Matplotlib There are three ways to customize Matplotlib: © Setting reParams at runtime. © Using style sheets, * Changing your maploibre file 20, Brief on Basemap tool kit Mapioaibs merci ‘his in data science is several Matplotib tool kits that are under the may ne semaP t0ol kit. This has Package implements many types of map project i 21. Write the features of seaborn Scts weve wm aetaeee plot style and color defaults, detee Pye, MPU that offers various choices fF plot types. and inteprates with on umBle bilevel fi rious choices | ith the fanctionalty provided gens, common statistical 4 y Pandas DataFrames. AY where Values are core mOvthed histo; The ‘ae a variety of smoothing techniques. Kernel, onctatated over een: Lo Kernel Density Eset me Some 1 Estimation (KDE) is on€ os vous yo vsvatznton a histogram. seaborn.histplot() is use to ph 1. Write Python program to plot Line chart by assuming your own data and explain the various attributes of line chart 2 Write python program to visualize the dataset using scatterplot and explain its parameters, 3. Elaborate the error visualization methods in pyplot. 4. Explain different methods of showing three-dimensional surface on & ‘two-dimensional plane with 5. Demonstrate the usage of histograms for data exploration and explain its tributes. laborate the concept of subplots and ications. i lott Discuss in details about the three plotting functions of matploti ‘module, tool kit for Geographic data Visualization. F Reterences ok",O'Reilly.2016. . JakeVanderPias, “PythonDataScienee Hand 2 ‘hutps://seaborn.pydaia.ore!

You might also like