Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
43 views44 pages

FODS Unit-5

The document provides an overview of data visualization techniques using Matplotlib, a popular library in Python. It covers various plotting methods including line plots, scatter plots, and customization options such as colors, styles, and annotations. Additionally, it discusses the importance of effective data visualization in data science for exploratory analysis and storytelling.

Uploaded by

aimlvsb
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)
43 views44 pages

FODS Unit-5

The document provides an overview of data visualization techniques using Matplotlib, a popular library in Python. It covers various plotting methods including line plots, scatter plots, and customization options such as colors, styles, and annotations. Additionally, it discusses the importance of effective data visualization in data science for exploratory analysis and storytelling.

Uploaded by

aimlvsb
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
You are on page 1/ 44
DATA VISUALIZATION Importing Matplotlib ~ Line plots — Scatter plots — visualizing errors j- density and contour plots ~ Histograms — legends — colors — subplots - text and annotation — customization — three dimensional plotting - Geographic Data with Basemap - Visualization with Seabor, 51 IMPORTING MATPLOTLIB significance in data science. It is used for many xs 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 yj how it is represented. What they represent component is just as important as the data. big difference. isualizations are what they represent and is the data to be visualized. The “how” The visualization technique can make a 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 ploting 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 h{1): import matplotlib as mpl import matplotlib.pyplot as plt Setting Styles The plt.style directive is used to choose appropriate aesthetic styles for the figures The classic style is set, which ensures that the plots use the classic Matplotlib style: 7 Foundations of Dat, ee 82 = se Inf2J: pltstyle-uset‘clasic') 6.1.1 Plotting trom a script If Matplotib is used within a SenPt Joop, looks for all currently active Figure windows that display the figures. then the function plLshow() stars Sheets and Opens One OF more Example # snes file: myplonpy import matplotipyplot as plt import mumps as mp x = npllinspace(0. 10, 100) pleplodx, np.sinix)) pleplor(x, np.costs)) ltshow) | ‘Run this seript from the commane-line prompt, which will result in g yi, opening with the figure displayed: te $ python myploupy . “The pltshow() command must interact with the system's interactive gray. backend. 5.1.2 Plotting from an IPython shell It ean be very convenient to use Matplolib interactively within an TPython gy Python is built to work well with Matplotlib if you specify Matplottibmode. To e, this mode, you can use the Smatplotlib command after startingipython: re In [1k Smanplotib Using matplotlib backend: TkAgs In (2): import matplotib.pyplot as ple 'At this point, any pit plot command will cause a figure window to open, ay further commands can be run to update the plot. Some changes (such as modi, properties of lines that are already drawn) will not draw automatically: to fora g update, use plt.draw(). Using pltshow() in Matplotlib mode is not required 5.1.3. Plotting from an IPython notebook The [Python notebook is a browser-based interactive data analysis tool that combine narrative. code, graphics. HTML elements. and much more into a siyi executable document. Plotting interactively within an [Python notebook can be dn) with the “matplotlib command, and works in a similar way to the Python se Option of embedding graphics directly in the [Python notebook: soli inline emai yi run this command (it fer YU needs to aa pithin the notebook that creates ae nly once per kerelession i embed a bre melsession), saint sraphic. 8 PNG image of the import mumps as MP wre mpdinspacet0, 10, 100) se = eefiguret) elon. msi.) ppl MP-c0s wl! Fig. 5.1 Example for Basic plotting 414 Saving Figures to File ft ene aon gues in 4 wide varity of fomats., Figures cin be a or example, 10 save the previous figure as a tS gsavefigt sine us png’) The file called sine_cos.png isin the current working directory: To display the contents of this file: WT}: from (Python display import Image Image 'sine_cos png’) Fig. 52 PNG rendering of the basic plot In savefig(), the file format is inferred from the extension of the gi ‘The list of supponted file types for the system ean be identified using uae method of the figure canvas object: Inf}: fig.canvas.get_supported filerypest) Ou}: f'eps": “Encapsulated Postscript’ ‘Jpeg’: ‘Joint Photographic Experts Group’. ‘pe’: “Joint Photographic Experts Group’, ‘pdf: "Portable Document Format’. ‘pes ‘PGF code for LaTeX’: ‘png’: “Portable Network Graphics ‘ps’: "Postcript ‘raw’: “Raw RGBA bimmap’, ‘reba’: “Raw RGBA bimap’ 'vg’t “Scalable Vector Graphics’ 'svgc's “Sealable Vector Graphics’ vif: “Tageed Image File Format’. ‘iff’: “Tagged Image File Format’) 5.1.5 Two Interfaces of Matplotlib © MATLAB-style state-based interfuce ‘* object-oriented interface te aoe oe a plot figure create 4 pI a first of #0 panels and set current axis 100 oA (rms, clu, pane! number f sxnpsints)) a “he second panel ond set current axis Fig. $3. Subplos using the MATLAB-tle interface + This interface is stateful: + Keeps track of the “current” figure and axes. Reference to these can be obtained using the plt.gcfi) (get current figure) and plt.gcat) (get current axes) routines, Stateful interface ix fast and convenient for simple plots Adding something to the first panel after creating the second panel cunnot be done, s1s2 Object-oriented interface ‘The object-oriented interface is available for more complicated situations and provides more control over the figure * Plotting functions are methods ofexplicit figure and axes objects, 56 a face axe more Te 1 clearly with split plotting, labeling © Object-oriented inte My Example ‘irst creat grid of plats Cn he 2.ax=pilt. sub (2) eae ax{ 1].plon(xnp.cos(x)): ‘. : : x ‘a 0s! 00 + Fig. 5A. sin and cos function 5.2 LINE PLOTS goin pleas scorer numpy as np all Matpotlib plots, a figure and For Tod axes. can be created 35 follows, ia, 18 created. In their simplest form, By —t Fig. SS An empty gridded axes Use the axplot function to plot the data wih: = wlfiquret) ‘ax = pluaxes() np.linspace(0, 10, 1000) acplorx. np.sin(x)): i0 ‘The pyplot, a sublibrary of matplali is a collection of functions that hes, creating a variety of chars. Line Plots are used to represent the relation between iy data X and Y on a different axis. ‘© Import Matplotlib.pyplot library for plotting functions. Import the Numpy library as per requirement Define data values x and y. Examples of a line chart in Python : ‘The simplest of all plots is the visualization of a single function y = f (9 Inf: Semanplotib inline import maiplottib pxplot us pt 195 Fig. 5.6 Simple sinusoid Foundations of Day ce * Il the plot function mun te re with multiple lines. al To create a single figut In}: pltplottx, np-sintx)) pitplor(x, np.costs))* 10 ig. 5:7 Overplotting multiple lines # Mutiipte plots on the same axis {import matplotispyplot as plt import mumpy as np x =npaarray{{I, 2, 3. 41) y art? # first plot with X and ¥ data leptons, y) xP =[2. 4. 6, 8) yt =(3. 5.7. 91 # second plot with xt and y! data pltplonx, yl. °") pltxlabelt"X-aris data") pltylabel("Y-axis dara”) plestle‘multiple plots’) lt show) 34s waded © 7 8 Fig. 58 Multiple plots ot Sating Line Colours and Styles ‘he plt.plot() function takes additional arguments si ig ty abst the color, color Keyword is. used sates een colors and sles sen ME virtually any imaginable color. The color can be specified in vain a wl: i, wpsinx - 0), color="blue’) hots, npssintx - 1), color='g') Pe ete 2 ere 825) alors. mpsin(x - 3). color="#FFDD44") Furor, npsinix - 4), color=(1.00203)) wix_mpsintx - 5), color='chartreuse') *# specify color by name # short cotor code (rgbemyk) # Grayscale between 0 and | f Hex code (RRGGBB from 00 10 FF) # RGB uple # all HTML color names supported 0 2 a 6 10 Fig. 5.9 Setting the color of plot Foundations of Data g, 5.10 — . ising the linesty!e ™ The line syle can be adjusted WANE ar Style Fsotid? efeul) |" dashed! = Fdashdot™ * None” ths Inf]: pleplott, x + 0, linesryte='solid’) pleplos, x + 1, linestle="dashed’) pleplots, x + 2, linesyle='dashdor’) pleplots, x + 3, linestyle='dotted’ # For short, you can use the following codes: pleplons, x + 4, lnestyle='") # solid pleplonts, x + 5, lnesyle= pleplots, x + 6, lnestyle= ages} a Fig. 5.10 Example of various line styles The linestyle and color codes can be combined into a single non-keynod argument (o the plt.plot() function as shown below: Inf: plepion x + 0. “R's # sold green pleplots, x + Le") # dashed «van ° 3 Fig. 5:11 Controlling Coors ad yh wh the hrthany syt Getting the Axes Limits of plots Default axes limits are chosen for the plot automatically, I yadpsing the axis Finis sing psi) ang Neg ee on sk: poplars, mpsin(x)) pltation( 1, WwW pleylim(-1.8, 15): 15 10) os i 00} 05 1.0 a8 o 2 « 6 68 © Fig. 5.12 Setting axis limits (1Df: pepo, mpsindadp plttim( 10, 0) pltslim( 1.2, -1.2): 5.12 Foundations of PE Se ‘The plt.axis() method allows to Fig, 513 Reversing the yousis passing a list which specifies (xmin, xmax, ymin, ymax]: Inf}: pleploss, mpsin)) pleaxis({-1, 11, 1 45 10) os oo 05 10) 5, 1S) set the x and y limits with a single a8 o 2 4 € 8 Fig. 5.14 Setting the axis limits with pltaxts 0 call, by The plt.axis() method allows to do things like automatically tighten the bounds around the current plot: Inf: pleplowx.np.sintx) pliaxist tight’): 5.13 Fg. 5.18 “tight layout itaxis()allows higher-level specifications, Ee on screen, one unit in x is equal Smee. ‘an equal aspect pups, p-sits)) Me asi ‘aul a 0 2 4 € io Fig. 5.16 An equal layout, with units matched to the output resoltion 524 Labeling Plots Labeling of plots with the titles, axis labels, and simple legends can be done wih the pyplt as below. The position. size, and style of these labels can be adjusted tsing optional arguments to the function. dM: pluplotts, np.sinix)) plesitle("A Sine Curve") plexlabel('<") ple ylubel("sintx)"I: 514 Inf 15}: pluplot(s, np.sinx), pltplot(x, np.costx), ltasis( equal’) plelegendt): FigS.18 Plot legend 5.3. SCATTER PLOTS Scatter plots are used to observe relationship between variables.Scatter plot iss type of plot in which the points are represented individually with a dot, circle, other shape instead of points being joined by line segments as in the case of a lie plot, The seatter() method in the matplotlib library is used to draw a scatter pl. Scatter plots are used to visualize the relation among variables and how change in one affects the other variable. . ti we 5.18 er ri ax for scatter() method is given below: Boars. as da, Jaxis_data, Fine, emap=None, Ynin=None, vmar=None ph og prs-None) oe vist ‘An array containing x-axis datg y.axis-data- An amay containing y-axis data ¢- color of sequence of colors for markers marker- marker style emap- emap name + linewidths- width of marker border + edgecolor- marker border color + alpha- blending value, between 0 (transparent) and 1 (opaque) ie seater plot thot mal plot as lt M18 7217294 1, 12 9, 6 Ay, 85 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86) ona» ¢ = "ble"? {fo stow the plot pt) 8a 8 8 8 Fig. 519 Seater plot 8.16 Int}: Smatplouib inline import maiplotlib,pyplot as pit pit.style.use( seaborn-whiesrid') import numpy as "P 5.3.1 Scatter Plots with pit.plot pltplovax.plot to produce line produce scatter plots as well Inl2}: x = npdinspace(0. 10, 30) y = mpsin(x) pluplowx, y, °0', color="black’ oo |. ynsout that ‘this same plots. functio, & os T =— 00 * 5 ig. 520 Scatter plot example ‘The third argument in the function call is a character that represents the ‘of symbol used for the plotting. Symbols such as '-" and control the line style, In{J: pleplor(x, y, “-ok'): # line (-), circle marker (0), black (k) Fig. 5.21 Combining line and point markers ord 517 onal keyw' arguments to pit.plot gait arkerst Plot specify a wide eh markers: range of ines . . Properties of w! paplots XP eolor="gry’ eee persize=15, linewidth: er ejacecolor= "white, 5 AI 5 2 1— Fig. $22 Customizing tne and point sumbers 542 Scatter Plots with pit.scatter ‘The plt.scatter function can be used to create scatter plots.The main difference so sai ert an ued a ne The main ie te properties of cach individual point (size, face color, edge color, etc.) ‘aividually controlled or mapped to data. “i mal we ge IWbl: pluscamtertx, y, marker=o' 70 5:18 Fg, 523 Simple seater plot Random ints of many colors and sizes is shown bg, sine nie results, alpha keyword is used to ager transparency level: Inj]: mg = np.randam RandomState(O) ‘mg.randn( 100) ig.randn(100) ‘mg.rand 100) 1000 * rng.rana( 100) pltscattert, y, c=colors, sesices,alpha=0.S.cmap= viridis") plicolorbart); # show color scale y color sizes Fig, 524 Changing size, color, and transparency in scatter points The color argument is automatically mapped to a color scale (shown hereby te colorbar() command), and the size argument is given in pixels. In this way, the coke ow ol ‘dt of colormaps in scatterplot = agores based on ther function: 1, Sequential: used for representing information Diverging: used when the informat > Yalue, such as topography or when that has ordering, Plotted has a critical mi the data deviates around zero. Cycle: used for values that wrap around atthe endpoi angle, wind diretion, or time of day, points, such as phase ualitativer used to represent inf & oun ips. nation which does not have ordering for instance, the Iris data from Sci Five types oF fIOWErs Whose sie of ts skleamdatasets import load iris A tod J) ares = irisdataT piscatterfeatures{O], features), alpha=0.2, s=100"feaures{3},c=irssarget, emaps viridis uslabeliris feature_names{0}) pelabeliri feature names{1}); sr a 45) = mpsings) + dy * aprandomrondn(30) ‘ea with a single Matplotib function egy Intl: int: plterrorbarx, y. yerr=dy. fnt="K') 3; {__j— — 74 Fig, $0 Errorbar example Using additional options. the aesthetics of the errorbar plot can be cu, Inf: pleerrorbartx. y. yerredy, fmnt='0", color='black’.ecolor=lightgray', elinewidh capsize=0): ae 3 Fig. $.31 Customizing errorbars eer a owes SS 9H ys error bands are a graphi i v ical repre onto around & main trace, rather than ay ayo MOF OF a oe implemented in a manne smart, isk pe fil attribute. a certainty as “ like error bars. Plots using scatter traces situations it is desirable to ip some show erro i oe a coat convenience rote fa tis quantities, wise {0 combine primitives like plplor ann’ 2 Ps aPBlaton, Heal BILAL between for a this, a simple Gaussian process re For APL. This is a method of fitings ot (CPR) is Performed ih 2 continuous measure of theuneenaing, ee taniee E certainty, ‘onparametric function fiom seamssusOn PCE Inpon CowsionPraes Mego he model ond dw some daw xc npasin(x) id= = mparray({l, 3, 5, 6, 8)) eo = modell) Fompue the Gaussian process fi a case ‘cubic’ theusO=1e-2,thetab=Je-4,iheta/=IB-, ged: mpeweis), la) t= aplinspacet0, 10, 100) A WSE = eppredictsfs mpnewasisl, eval MSE=Te) = 2 * mpsgrtMSE) # 2sigma ~ 95% confidence region ‘The arguments xfit, yfit, and sequel lobe pert finn Bt pong a0 oes is, aoe jax possible. Instead, the plLfill between function can be used with a light color ty visualize this continuous error Bi # Visualize the result pltplot(xdata, ydata, “or') pleplontfic, xf, '-", color='gray") pitfill berweent fit, sfit «dit. yf + daft color= ‘gray’, alpha=0.2) plrxlimi0, 10%: 5.26 10 pceting commons wacertanty wi filed replng ction an x value, the lower y-bound and the y, area between these regions is fjet May very intuitive view of the Gaussian Fig. 5.32 Ret In the fill between fun are passed, and the result is that the ‘The resulting figure gives @ regression: + In regions near a measured data point. the model is strongly ‘and this is reflected in the small model errors. © In regions far from a measured data point, constrained, and the model errors increase. ons, the model is not sg 5.6 DENSITY AND CONTOUR PLOTS Contour plots (sometimes called Level Plots) are a method to three-dimensional surface on a two-dimensional plane. It represents two variables X ¥ on the y-axis and a response variable Z as contours. These om ‘are sometimes called the z-slices or the iso-response values. mon show 5 ‘A contour plot is appropriate to view how the value of Z changes as a fy of two inputs X and Y, such that Z = f(X.Y). A contour line or isoline of - 2 of two variables is a curve along which the function has @ constant valyen The independent variables x and y are usually restricted to a regular grid cay ‘meshgrid. The numpy.meshgrid creates a rectangular grid out of an array of x vl and an array of y values. pa Matplotlib API contains contour() and contourf() functions 10 draw contour ling and filled contours. respectively. Both functions need three parameters xj al zplt.contourf : for filled contour plots ltimshow ‘fur showing images. plteontour for contour ploxs pitcontourt for filled contourpiy pltimshow for showing images natplrt inline we ip inport matplotib,psplor as pt pustylesel‘seubornwhite’) inport mumps asp 1 Vovalizng a ThreeDimensional Function A contour plot is defined by using a function 2 = fi, y, we Wf fis 3 renurn mpsindx) ** 10 + npcos 0 + y * x) © npcostsy + A-contour plot can be created with the plt.contour function. + It takes three arguments: grid of x values i + Values, grid of y values, and grid of z values. The x and y: values represent positions on the plot and then values will be represented by the contour levels, Bio and he Choosing a colormap is just the first step. Deciding among the po ‘more important usin choosing the coformap ze tee different categories of colormaps sequential colormaps: These consist (eg. binary or viridis) 541 : of one continuous sequence of colors Divergent colormaps: These usually contain iwo positive and negative deviations Qualitative colormaps: rainbow or jet). distinct colors, which show from a mean (e., RdBu or PuOn, ‘These mix colors with no particular sequence (c.g., The jet colormap, which was the default in Muplotib prior to version 2.0, is yample of a qualitative colormap. Its status. as. de detent a abs slormneecase Gulalive MPS ae often a poor choie for pases ‘eaatie date ‘Among the problems is the fact that qualitative maps usually do not displ saform progression in brightness as the scale increases. ° may Converting the jet colorbar into black and white (51: fox maplenclot impor LinearSqmenedClomap fe wrt ele ep Return a grayscale version of the given colormap"” ae HU pe cecelep sa ener come city Touven ROBA 10 perceed grjsahosiaace ¢{mplenrydeiex comp hand GBweight = 10.299, 0.587, v.114) Imice = npsgrtnpdotclor. 23) * 2, RGB weigh) ilo» lawl) apeontp stam LinerSeentedColormap rm ie cmapume + “gay i vewolormaplomap “Ph eulonnan sth ts greyscale eget” =p tt lecte eis = emuptaparenetomap§) tem sryinale smatemay} colors, emap.N) cmapinp arangetemap.N) fit ax = ple subplons(2, figsize=(6, 2) ‘abplon kw =dicw xticks=| |. sticks=11)) Foundations of Day, ne St Data 6.42 ae Sey 10,0 HN) ax{0}.imshow(feotors), extent=10, emo xf imshowi{grayscale). extent=I In [6}: view colormapt jet) Fig. £50 Jet colormap and is uneven lominance scale Color limits and extensions + Maiplotib allows for a large range of colorbar customization, The Colo is an instance of plLAxes. hy ‘©All of the axes and tick formatting are applicable. «The colorbar has the flexibility t0 narrow the color limits and ing, out-of-bounds values with a triangular arrow atthe top and bottom by the extend property ing Discrete Color Bars Colormaps are by default continuous, but can be represented with discrete ya The easiest way to do this isto use the pltem.zet_emapt) function, and pase name of a suitable colormap along with the number of desired bins: Inf | + pltimshow(1, emap=plt.m.get_cmap\ Blues’. 6)) plecolorbart) plectim(-1. I) visualization St Fig, 5.51 Discretized colormap I is necessary to compare different views of data side by si , i ide. Me it seme ps ap fee le ey May nas jgue. These subplots might be insets, grids of plots, or other more compliented yout wills Smaxplotlib inkine import matplottib,pyplot as pit aie incon ay as Ing axl = pleaxes() # standard axes ax2 = pliares({0.65, 0.65, 0.2, 0.2)) to ae | % oa # | % ol | 0a| | of Fig. 5.52 Example of an inset aves Foundations of Dayy 544 Inia: fi pire) scab linet 12, 12) x2 = fig.add_axes(0.1, 01,0! Mim=(-12, 12) x = npdinspace(0, 10) axl plorinp.sints)) axzplonmcodsys 17 oSS™S as 09 05 410 109] 25 00 05] 10) 1, 05, 08 04! 08, 041, 0 10 20 - Fig. 553 Verially stacked axes pit.subplot: Simple Grids of Subplots pit subplotereates a single subplot within a grid. This command takes integer arguments—the number of rows, the number of columns.and the i plot to be created in this scheme, which runs from theupper left to the bottom nls}: for iin range(}, 7): plt.subplow(2, 3. i) pletext(0.5, 05, str(2, 3, i), fontsize=18, has center’) ine of te Tight 5.45 oe loa wor ol oy _ a 2.3.1 on aa, * = ‘eas | * | “oozes voor Nhe ~ 19, os al al oe | 23,4) “ oa oa! ol 02 | ‘. oa) 0 #4 subplots that span mult le rows oem vnnuspen Sand columns, can be drawn using Object does ui i Tot create a plot byitself; it is simpl Favenient imerface that is recognized by the pltsubplor me oe To's of two Tow and thee cues oe fem 3 ant space looks like this: lumns withsome specified width and ed ain pl.GridSpec(2, 3, wspace=0.4, hspace=0.3) From this we can specify subplot locatic us ‘ ne ea fons and extents using the familiar Python plesubplot(grid[0, 0) fo gridfO, 1:) pesubplon grid |, :2)) pesubplot grid 1. 2)) 7 as “| L | 02 “hammer Teoa10 “bo wo 0 |» in | | 0 02 0002 0a 08 os 10 Soars asesio Fig.SS5 Irregular subplots with plUGridSpec a Foundations of Datg cum sd. alignment bas 2 Wi ‘This type of flexible grid ligne 5.11 TEXT AND ANNOTATION pain Cer, Good visualization guides the WE! rely visual manner, without theay cases this tory cn be PET xual cues and abet re necessary. The et text, but in others, Of annotations are axes labels and tiles Inf}: Sematplotibinkine Jmport manpottio,pyplos as Plt import maxplotto as mol lt style set ‘seaborn-whiegrid') import nunpy 0s "? import pandas as pd Example: Effect of Holidays on US Births Int2h births = pé.read esx ‘births.cs") quartiles = np.percentile births births, (25, 50. 751) yuariles(1), 0.74 * tquarttes{2} - quarttes(0)) binths = binhequer( (inks @mu - 5 * @sig) & (births Gru + 5 * @sigy) binths{'day"] = births{ ‘day’ Lastypetint) births index = pel.to_dotetime(10000 * births.year + 100 * births month births day, format="%¥Sem%d') births by date = births.pivot_table( ‘births’. [berths index:month, births indexday)) births by date.index = [pd.datetime(2012, month, day) ‘for (month, das) in births by. date index] Inl3]: fig, ax = plesubplots{figsize=(12, 4)) births_by date ploar=ax): . cs Fig. 5.56 Average dally births by date itis required to annotate certain features of the plot to draw the user's attention, sis can be done manually with the plttexvax.text command, which hich will place text walt fa. ox = pltsubplotfigsice sinhs_by date plot(ax=ax) 4 Add labels 10 the plot anle = dict{size=10, color='gray') agctest("2012-1-1', 3950, "New Year's Day axtet(2012-7-4', 4250, “Independence Day", ha='center’, **style) cextent("2012-9-4", 4850, “Labor Day", haz'center’, *style) axter{'2012-10-31", 4600, "Halloween", ha'right’, **style) exten'2012-11-25", 4450, "Thanksgiving", ha='center’, **syle) acest 2012-12-25", 3850, "Christmas ", ha='right’, **style) # Label the axes axsettile='USA births by day of year (1969-1988)" vlabel='average daily births) # Format the x axis with centered month labels ‘acxaxis.set_major_locator{mpl.dates MonthLocator()) 12, 4) ‘axxaxis.set_minor_locator(mpl.dates MonthLocator{bymonthulay=15)) axzatis.set_major formatter(plt.NullFormatter() ‘axxaxis.set_minor_formatter( mpl dates.DateFormattert eh’) rig, $57 Anootted average daily births by date position, a y position, a string, and ‘The axstext method takes 2 * Fle alignment, and other then keywords specifying the color, size, Properties of pnw Note: tas and heen’ where fs short fOr Horizon apna X 5.11.1. Transforms and Text Position Anchoring the text to a postion on the axes or figure, independenar can be done by modifying the transform. Any graphics display framework eed fy scheme for translaing between coordinate systems. For example, a data pon 2% y) = Il needs to somehow be represented at a certain location on the figure, aq in tum needs to be represented inpixels on the screen. Wig There are three predefined transforms axtransData :Transform associated with data coordinates axtransAxes: Transform associated with the ates (in units of aes dimensions) {figsransFigure Transform associated with the figure (in units of figure dimensions InlS}: fig. ax=plt-subplotsfacecolor= lightgray") axcaris(0. 10, 0, 10)) # transform=axiransDaua is the default, but we'll specify it anyway axten, 5, * Data: (1, 5)", transform=ax.transData} axtesnO.5, 0.1, * Ares: (0.5. 0.1)" saxtestO.2, 0.2, °. Figure: (02, 0.2 transform= fig ransFigurey iransform=ax.transAxes) 70 Fig 558 Comparing Matplotib’s coordinate systems 112 Arrows and Annotation Drawing arrows in Matplotlib is much harder pltarrow0 function: the arrows itereates are SVG woke varying aspect ratio of the plots, plannotate() function: This function ows are flexible. objects that will be subject teates some text and an arrow, and the ‘The arrow style is controlled through the arrowprops dictionary yt l: Semasplotbinkine sx exeplisubplots() rexplinspace(9, 20, 1000) axpltts, mp.c0s(t)) sxatis('equal’) examotate local maximum’, xy=(6.28, 1), xytext=(10, 4), twrnectionstyle="angle3,angleA=O,angleB=-90")); 550, 5.12 CUSTOMIZATION 5.12.1 Customizing Ticks ib’ ; S are designed Matplotlib’s default tick locators and formatters are designed to by sufficient in: many eommen situations, but are ia no Way optimal for ever nc Major and Minor Ticks Within each axis, there is the concept of a major tick mark and mark. As the names would imply, major ticks are usually bigger or more while minor ticks are usually smaller. By default, Matplotlib rarely minor ticks, but one place you can see them is within logarithmic plots InlIl: ematptotlib intine import matplotlibpyplot as plt plt-syleuse ‘seaborn-hitegrid’) import rumpy as np Inf2}: ax = pluaxes(xscal 8 minoy Cy Proncuay MAKES ye “log’, yscale="log') we 107 108 10 108 08 0? F259 sample opt esate ik 16 ind munber of muliples of pi2 N= intlnp.round(2 * value / np.piy) 1 func(value, tick number): aN == I: retum r'Dpir2s" return r'Spi5"* iN % 2 0: returnr"S[ON/28" formaatN) else: renurne’S{ORPiS” formant / 2) ccsssset_major formatter pl FuncFormatter(forat_func)) rig, $61 Ticks with custom labels 5.12.2 Customizing Matplotlib i hea ity release, there is an ebility tO customize defayi, with aesthetic preferences. Plot Customization by Hand Stig, tweak individual plot settings to end up with so, Sous a weviow than the default. It's possible to do these conga tty each individual plot. Inf}: import masplotib.pyplot as plt lt style.use(‘clasic') import numpy as np maiplotib inline In[2}: x = np.random.randn( 1000) leis: ot @ Fig. 5.62 Histogram in Matplotib's default style yeualzation. ess OP pockgrownd feo rishe= #EOESES') oF rlow(True) valid white grid lines 190 clor=', linesiyle=' solid’) ions 4 in axspines.valuest): pre spine.set_visible( False) ie tp ond right ticks vissick bottom) sick Ie) es ticks and labels 5_porams(colors="gray’, direction="out') ack in ax get_xticklabels(): Fr" jgkset_color"gray’) pe tick in get stildabes: sick set_color{’gray") feottrl face and edge color of histogram hints, edgecolor="#ESESES', color="#EE6666); 250. | 200 | 10} +00! rr ee ee) Fig. 563 Histogram with manual customizations There are three ways to customize Matploti: 1, Setting reParams at runtime. 2 Using style sheets 3. Changing your matplotibre file yy Foundations. of 20a sind a rcodence over style sheets, sty, a ey Seting rParams trie takes Pe a ee ting precedence over matpiouibe Mes time configuration) settin i the default ro (v0 "BS in g ” dynamically change | seript or interactively from the p> \ | import numpy as np import matploitib.pyplot as plt 004 import matplottib as mp! rm xcler import exer | +) rpc Parans ies init’) =2 mplrcParamsf tines linestyle'] =" | SS dxa=np randon.randn(50) a pleplowdata) Fig. 5.65 ‘The geplot style ‘The matplotlibre file Maiplotib uses matplotlibre configuration files to customize alll kinds of eries is called ‘ve settings’ or “re parameters’. We can control the defaults of {ost every property in Matplotlib: figure size and DPI, line width, color and style, axis and grid properties, text and font properties and so on. The matplotibre ic ead at startup to configure Matplotiib. pak background For figures used within presentations, it is often useful to have a dark rather tun light background. The dark background style provides this Fig. 5.64 Line style in Histogram Wl: witplestyle.contexi ‘dark background!) ta ad_lines) 5.12.3 Using style sheets Another way to change the visual appearance of plots is to set the rPaane | SMM a so-called style sheet and import that style sheet with matplotlib.style.use, ‘The grayscale style can be drawn as: AA style sheets looks the same as a matplotlibre file, but in a style sheet ye gq | ll withollsle.comtet grayscale’ ‘only set rcParams that are related to the actual style of a plot, ‘tist_and_tines() ‘There are a number of pre-defined styles provided by Matplotlib. For ‘example, there's a pre-defined style called "ggplot", which emulates the aesthetics Of geplot (x 18, THREE DIMENSIONAL PLOTTING popular plotting package for R). To use this style, add: Matplotlib was initially designed with only two-dimensional plotting. Around the lt.style.use("geplot’) . lime of the 1.0 release, some three-dimensional plotting utilities were built on top of all Wieiphniaeanied Matplotlib's two-dimensional display, and the result is a convenient (but limited) set + witplesyte contest ‘ggptor’) of tals for three-dimensional data visualization. Three-dimensional plots are enabled hist_and_lines() by importing the mplot3d toolkit, included with the main Matplotlib installation

You might also like