0% found this document useful (0 votes)
106 views

Matplotlib

matplotlib with python

Uploaded by

Vijay Dubey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
106 views

Matplotlib

matplotlib with python

Uploaded by

Vijay Dubey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 20
Python Plotting With Matplotlib (Guide) byBtadSolomon ®30Comments > [Gaas)(Gmcsiase) Mark asCompleted Table of Contents Why Can Matpltlib Be Confusing? ‘Pylab: What sit, and Should 1Use I? “The Matootib Object Hierarchy. Slatful Versus Stateless + The figures” Behind 1 ‘Appendix: Configuration and Styling ixB: Interactive Mode Opancizads [EATEN This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Plotting With Matplot “Apicture is worth a thousand words, and with Python's matploti library it fortunately take far less than a thousand words of code to create a production-qualty graphic. Improve Your Python However, atplotiis also a massive library, and getting a lotto lookjustrightis often achieved through tial and error. Using one-tinersto generate basic plots in matplotii is fay simple, bt skilfully commanding the remaining 98% ofthe ibrary can be daunting. Thisarticleisa beginnerto-intermediate-evel walkthrough on matplotib that mixes theory with examples. While learning by example canbe tremendously insightful it helps to have even just a surface-level understanding the brary’ inner workings and layout as wel Here's what well cover: + Pylab and pyplot: whichis which? + Key concepts of matpletlb’s design Improve Your Python + Understanding ott. subplots() 3} Python Trick code snippet every couple of days: + Visualizing arrays with matplotip sith afresh + Plotting with the pandas + matplot Email Address Free Bonus: Click hereto download: 2 a bass for making your own plots 2 ‘Thisarticle assumes the user knows tin, - ata, drawing samples from different statistical distribution instalee, see here fora walkthrough before proceeding. Learning matpltlb canbe a frustrating process at times. The problem is not that matpltib’s documentation is lacking: the documentation is actualy extensive, ut the following issues can cause some challenges: + The library itself is huge, at something lke 70,000 total lnes of code, + Matplotib is home to several diferent interfaces {ways of constructing figure) and capable of interacting with handful ofeitferent backends. (2ackends deal witn the process of how charts are actully rendered, not just structured internally.) + White itis comprehensive, some of matpoti’s own public documentation is seriously out-of-date, The brary still evolving, and many older examples floating around ontne may take 70% fewer ines of code in their modern So, before we getto-any ality examples, its useful to grasp the care concepts of matpotlibs design. ‘Master Real-world Python Skills ‘ith a Community of Experts Level Up With Unlimited Access fo Our Vast Library ‘of ython Tutorials and Video Lessons Watch Now » Pylab: What Is It, and Should I Use It? Lets start with abit of history: John D. Hunter, a neurobiologst began developing matplotib around 2003 originally inspired o emulate commands from Mathworks’ MATLAS software, Jahn passed away tragically young at age 4, in 2012, ane matpotib is now afullledged community effort, developed and maintained by ahostof others. (John gave a talk about the evolution of matpotib atthe 2012 SeiPy conference, which is worth a watch (One relevant featur of MATLAB\isits global style. The Python concept of importing isnot heavily used in MATLAB, and ‘most of MATLABYS functions are readily available to the user at the top level, Knowing that matpltlb as its roots in MATLAB helps to explain why pylab exists. pylab isa module within the ratploti library that was bull to mimic MATLAB' global syle. elsts only to bring 2 numberof functions and classes from both NumPy and matplotib into the namespace, making for an easy transition fr former MATLAB Users who were not used to needing ingort statements, [ExMATLAB converts (who areal fine people | promise! ked this functionality, because with from pylab snport they could simply eal plot) orarray() directly, as they would in MATLAB. ‘Thessue here may be apparent to some Python users using ron pyleb import “Ina session or scripts generally bad practice. Matpotib now directly advises against this in its own tutorials: “Ipylab) still exists for historical reasons, butts highly advised not to use tpollutes namespaces with functions that will shadow Python builtins and can lead to hard-to-track bugs. To get IPython integration withoutimports the use ofthe anatptot1sb magic is preferred." [Source Internally there area ton of potentially © ‘oython ~-pyab from the terminalfcom ort * under the hood. Improve Your Python sth afresh > Python Tick 2 The bottom nes that matplatib has al ‘cove snippet ever couple of days: against using pylab, bringing things mo cmaaadvess Without the need fr pylab, we can usual Python While we're ait let's aso import NumPy, which we'l use for generating data later on, and callnp. randon. seed) £0 ‘make examples with (pseudorandom data reproducible: thon 29> prandon seed) The Matplotlib Object Hierarchy Cone important bg-picture matplotb concept ists abject hierarchy. I you've worked through any introductory matplotliptutoral, you've probably called something lke ptt. plot(2, 2, 2). This one-liner hides the fact that a plots really a hierarchy of nested Python objects A“hierarchy" here means that there isa tree-ke structure of matplotlib objects underlying each plot. /Arigure objects the outermost container for a matplotlb graphic, which can contain multiple wees objects. One source af confusions thename: an axes actually translates into what we think of35 an individual pos or graph rather than te plural of “axis,” as we might expect) ‘You can tink of the Figure object as aboxcke container holding ne or more Axes (actual pts). Below the nee in the hierarchy are smaller objects suchas tick marks, individual Ines, legends, and textboxes. Almost every “element” ofachartisits own manipulable Python object, all the way down tothe ticks and labels: Figure Heres an illustration ofthis hierarchy in action. Don't worry if you'e nt completely familiar with this notation, which well cover lateron Python D> ig, _ = pt smpletscy >>> sypotiey ‘Above, we created two variables with it.suplots()-The isis atoplevel igure object. The second isa “throwavay?vatablethatwe dont neediest anand uith an nareron iin at tating He nnn traverse down te igure hierarchy and st Improve Your Python ) Python Trick 3 code snippet every couple of days: sth afresh stick = fig.anes{0] yards. get, >>> typetone te) Email Address Above, fig a Figure class instance) has yanss and xaxs, each of which have a col Matplotib presents this as a igure anato (totrue matploti style the igure aboveis created inthe matplotlib docs here) Tes Mi the » raha Online Python Training for Teams Oemeseads Stateful Versus Stateless Approaches Aight, we need one more chunk of theory before we can get around tothe shiny visualizations: the cifference between the stateful state-based, state-machine) and stateless (object-oriented, 00) interfaces. Above, we used inport eatplotiib.pyplot as pit toimportthe pyplot madule from matplatlb and nameit pit ‘Almost al functions from pyplot, such as pie p2ot(}, are implicitly ether referring toan existing current Figure and current Axes, or creating them anew if none exist Hidden inthe matplotib docs this helpful snippet: {With pyplot, simple functions are used to add plot elements nes, images, text, etc) tothe current axes in ‘the current figure. [emphasis added] Hardcore ex-MATLAB users may choose to word ths by saying somethinglike,*pls.plor() is state-machine interface that implicitly tracks the current figure!” In English, tis means that + The stateful interface makes ts alls with pit. ple) and other top-level pyplot functions. There is only ever one Figure or Axes that you're manipulating at agven time, and you don't need to explicitly refer toi ‘+ Modifying the underying objects directly isthe object-oriented approach. We usually do this by calling methods af anaxes object, whichis te objec Improve Your Python The flow ofthis process, ata high evel, le sth afresh 3} Python Trick [eee code snippet every couple of days: Email Address ‘Tying these together, most ofthe functio: ‘Thisiseasierto see by pecking under the >>> dat plot args fe gea0) ecurn ae plos(-ares, *oares) 5) Doo dof geahrgs) turn pltgc#()-2caCorenaegs) Calling 1¢.plot() is just a convenient way to get the current Axes of the curent Figure and then callitsplot() ‘method. Thisis what is meant by the assertion thatthe stateful interface always “implicit tracks" the plot thatit wants toreference, pyplot shome toa batch af functions that are really just wrappers around matpotib’s object-oriented interface. For example, with pit.title(), there are corresponding setter and getter methods within the 00 approach, 10() (Use of getters and setters tends to be more popularin languages such as Java but is 2 key feature of matpotibs 00 approach) au set sitet) and ax. gett -titlet) gets translated into this one line: gca()-set_titie(s, *args, *shwargs). Here's what thats e() is setter method that sets the title for that Axes abject. The “convenience” heres that we didn't need to specify any Axes object explicitly with pie. tstiet) Similarly, fyou take few moments to look atthe source for topevel functions ike ls. plt.yabe1s(, youll natice that all of them follow the same structure of delegating then calling some method ofthe current Axes. (Thisis the underiying object-oriented approach! gend(), and cat) and the euren Understanding p1t.subplots() Notation Aight, enough theory, Now, we're ready to tie everything together and do some plotting, From here on out, we'll ‘mostly rely on the stateless (object-oriented) approach, which is more customizable and comesin handy as graphs become more complex. The prescribed way to create a Figure witha single Axes unde the 00 approach s (not too intuitively with pit.subplots(. This is really the only time thatthe 00 approach uses pyplot to create a Figure and Aes: >>> fits ax = ple. suplots(> ‘Above, we took advantage ofterable unpacking to assign a separate variable to each of the two results of plt.subplots(). Notice that we didn't pass arguments to subplots() here. The default cals subplots(arows-2, reolse1). Consequently, axisa single txessvoplot object: thon >>> ‘ypetand Improve Your Python We can callitsinstance methods to man a stacked area graph of three time series: 5} Python Trick code snippet every couple of days: sth afresh Python o> me = apsarmen(se) Emailaddress >>> me = ap randon.randint(®, 18, 51 >>> 4p, ax = pt. svplors(Festze-(5 de> persteexplor(yrs, tag = ond, labessy canconie doo mecnet title( combined cent growth over tine!) >>> ae lagend(Lo=' ope” Leet") Doo pecset ylabel("Torat Seb") 23s peret inGaninyts(@], smaeyesl a1) >>> Fag tant Layout() Here's what's going on above: + After creating three random time series, we defined one Figure (rig containing one Axes (a plot, 2) + We call methods of ax directly to create a stacked area chart and to adda legend, tte, anéy-axs label. Under the object-oriented approach, it's clear that allo these ae attributes ofa. + eighe_tayout() applies tothe Figure object as a whole to clean up whitespace padding, Combined debt growth over time PO) mm Oceania B34 2 Lets look at an example with multiple subplots (Axes) within one Figure, plotting two correlated arrays that re drawn from the ciscrete uniform distribution >>> X= mpinandon rancine (low, Nah, size) doo y = nm.randan.randet(t, 5, s8ze%size) 29> data ~ apicolunnstaex((x, 99) b> fig, (2, 92) = ple aplota(rraues, eaten, fasize-(s, ©) oo mscatter(nen, yoy, aakers'o", ce'e', edpecolorsb) vos pen get title( scoters inh veneer 86°) >>> ae Set eabel ss") >>> we set ylabel 35°) >> weznist(data, ninsong-arangetdet Improve Your Python Tabel-'s 9) >>> ax. Legend(loe-(0.65, 8.8)? .with a fresh 3 Pythen Trick >>> a. set tte Frequencies of $x code snippet every couple of days oss pe yards tek rent) Email Address Scatter: x vi vee +e een ] 2 ‘There's a tle bit more goingon inthis example + Because we'te creating a“1x2" Figure, the returned esult of pit subplots(2, 2) isnow a Figure abject and a NumPy aray of Axes objects. (You caninspect this with ig, axs = ple.sueplots(2, 2) and takinga look at 2x5) *+ We deal with axa and axa individually, which would be cificult todo withthe stateful approach. The final ine isa 00d illustration ofthe abject hierarchy, where we are madifying the yexis belonging ta the second Axes, placing its ticks and tiekiabels tothe right. + Text inside dollar signs utilizes eX markup to pu variables in italics. Remember that multiple Axes can be enclosed inor "belong to” agen figure. In the case above, Fig owes gets usa lista the Axes objects oo» (fag sees[0] 45 ae, Fe acest] 4s a2) (ve, Tove) (sx. axes is lowercase, not uppercase There's no denying te terminology is abit confusing) ‘Taking this one step further, we could altematively create a figure that holds a 2x2 grid of tees objects: Python > D> Fag, Ok = pe ubplote(mrone 2, meets 2, Figsize-(, 79) Now, what 2x2 i's no longer single wees, but 2 two-dimensional NumPy arta of them >>> eypeton) srray{[[enatplot1ib.otes._sutplots.AxesSubplot object at &422064a638>, “matplosLsb.sxas, splat. AxesSubplot object a @a130117495)] ecipenonsect) oo Improve Your Python This is reaffirmed by the docstring sith afresh 5} Python Trick code snippet every couple of days: “pecan be ethera single natpiot1i created” Emailaddress Wenowneed plotting methods on case). common way to address thisist Doo Hig, ax = I seplos(orons2, neols-2, #3E852e-(7, 7) D> web, 0, OG, as ae Flatten?) een 2 24 NPY array co ad We could've also dane this with ((axt, 242), (ax2, ax4)) = ax, but the ist approach tends to be more flexible, Toilustrate some more advanced subplot features, let's pull some macroeconomic California housing data extracted from a compressed tar archive, using 4, xarféle, and unl from Python's Standard Library. Python > Sytest0fertopen(urt) read} D> with tanfte openfnoges's, eabj:b) as archive: housing ~ na loaétnt{archive,extractfile(fpath), deliniter-',") ‘The “response” variable y below, to use the statistical term, isan area's average home value. pep and agearethe area's population and average house age, respectively D> y= heusingtts 2) 25> pop, age = housings, [4 711-7 Neat let's define a “helper function” that places a text box inside ofa plot and acts as an “n-pot title’ D> df aed ttehebor(an, text) Se Fent(.55, 8, tent, Ssse', aloha.) fontsize-22-5) We're ready todo some plotting. Matplolb's gsassac module allows for more subplot customization. pyplots supplotzgrie() interacts with this module nicely Lets say we want to create a layout lke this Improve Your Python .with a fresh 3 Pythen Trick code snippet every couple of days: Email Address ad oe. axt oes 204 ‘ 0s ax Above, what we actualy haveis 030g columns and two rows oT 1 joe. 1 Vo6 uy 1s eS RE ee ios : 1 \ 1 oes 1 ' 1 1oo+ + ' 1 Peon sw Ly Toy ho ' Vos. a tos ! 1 1 1°%.5 92 es oo 0 104°%G0 aa ! Loe et ee oe 1 OP or ok ge Be 38 1 ‘The second argument to subplotagrid) isthe (ow, column) Location ofthe Axes within the gi o> enidsize = (3, 2) >> ig = alt. Figure rigsize-(22, 89) Doo aah pt supletagridgrisize, (0, 0), colspan2, rawspan2) 23s we = pt seplotzeria(eriersze, (2, 9) >>> aa = pit sumpletamiaceresize, (2, 0) "Now, we can proceed 2s normal, modifying each Axes individually: boo meh seb ite Hone font size-28) aut. seatter(seage, ¥-po pit colorvar(s bes Set_yscalet Sos ez nese age, ines eB nistteop, bins 200 nario") ste") doo adé_tilebox(ae, aee_tittenox(a03, istoa (doe set.) Home value asa function ofhome age (X-axis) & area population (Y-axis) Improve Your Python . sith esh 3) Python Trek 9s Tt code sippetever couple of day: we. os Email Address ‘Above, coLervar() (diferent from ColorMap earlier) gets called on the Figure directly, rather than the Ate. sf argument uses Matpltlb’s .scatter()andisthe result of ax.scatter(), which functions asa mapping ofy-values a Colona. Visually, there isn’t much differentiation in color (they-variable) as we move up and down they-axls, indicating that home age seems to bea stronger determinant of house value, Real Python for Teams » The “Figures” Behind The Scenes Each time you clit. subplots) or the less frequently used pic. +igure() (which creates a Figure, with no Axes), you ‘are creating 2 new Figure object that matplotlesneakly keeps around in memory Earle, we alluded tothe concept ‘of current Figure and current Axes By default, these are the most recently created Figure and Axes, which we can show with the builtin function sat) to cisplay the address ofthe objectin memory >> igh, aa = ple sumpletsey >> ss¢Hien) doo td(oltigetOo) # “Fer As the current Are >> fie, a2 = ple. subplots. doo Ld(Higa) = id(adt.gefO) 4 The current Figure has changed bo “Fig (ve could also use the builtin ix operator here.) After the above routine, the current figures 42, the most recently created figure. However, both figures are till hanging around in memory, each witha corresponding I number (indexed, in MATLAB styl}: >>> pt get_Fignans ta ‘useful way to get all of the Figures themselves is with a mapping of ple. rigure() to each ofthese integers: >>> de get_ald_tigures(y retson [plt-figure(s) for £ Sn plt-get_FSgnans()] >>> get at flesres Centploiitigre igure 9 daar Improve Your Python sth afresh 3 Python Trick Be cognizant of this eunning a script wh code snippet every couple of days them ater use to avoid aeroryErrer. By rpumbernun, and pt. close('312") close: Email Address Python bop pt etase(“al") >> got a iaores) i A Burst of Color: imshow() and matshow() While ax.pior() is ane ofthe mast common plating methods an an Axes, there area whole host of others, aswell (iveused ax. stackplot() above, You can find the compete list her) Methods that get heavy use ae inshou() and matshox(), with the latter being a wrapper around the former. These are Useful anytime thata raw numerical array can be visualized asa colored grid First, e's create two distinct grids wi some fancy NumPy indexing: Python bos x = mpataglop.aranget, 22))022-1, D> a etag_andices fren(x(=!-1))] = p.arangel2, 22) oo 2 np aranga(e size) reshape shape) Next, we can map these to their image representations, In this specific case we toggle “oll” all axis labels and ticks by using dictionary comprehension and passing the result to ax. tick parans() bop sides = (Lett, “rapes “tops “botten'y oso molabels = (5: false for's in sides) doo molavels.opeate(("1sbelks) X81 False for sin siees)) ne(nonabels) (eft; False, ‘night's False, “taps False, “bo False} ‘Then, we an use a context manager to cisable the grid, and callnatshout) on each Axes. Lastly, we need to put the colorbarin whats technically anew Ates within rig. For this, we can use abit ofan esoteric function from deep within matploti: ooo with plt.re_eontoxe(re-(sen gia: False) fig, (art, 2:2) = ple sibplotstt, 2, figsize-(8, 4)) sua natstowts) fing? = wx2-natshon(, enape'2eVion.') for ax in (@xd, 292) bt tlck_parane(atise “both”, whieh "both’, “tnalabels) for 8, 4 an riot x-ranters) eastenttJ, 4, m(Ss J}, cOl0"—"ahite!, man‘center", vac‘center") oc cuvter append nes( Improve Your Python fi scolrber (ing eaeany# Far oriiet nentane wih with afresh ) Python Trick 3 code snippet every couple of days: Hea Email Address 6 20 URC Plotting in Pandas ‘The pandas library has become popular fr not jus for enabling powerful dats analysis, but also forts handy pre canned platting methods. Interestingly though, pandas plotting methods ae realy ust convenient wrappers around existing matplotib cals ‘Thatis, the plott) method on pandas’ Series and Datafvame's 3 wrapper around pit.plat()-One convenience provided, for example, is that ifthe DataFrame's Index consist of dates, ecf().autornt_xdata() is calledintemally by pandas to get the current Figure and nicely auto-format the xos In tur, remember that pis. pio() (the state-based approach) is implicitly aware ofthe current Figure and current ‘nes, So pandasis following the state-based approach by extension We can prove this chain” of function calls with bit of introspection, First let's construct a plain-vanilla pandas Series, assuming were starting outin afresh interpreter session: pandas a5 oa >> 5 = pe Sertes(ng. oranges), de os aes pot see(9860'9) >>> sypetan) ‘enatgloe1i9.0%65,_subplots.AsesSubplot at @xI21085eb6> bo» soit aca) ~ S000) Thisinterma architectures helpful tok Improve Your Python cals, whichis done below in plating the Series fr which we ca alla. 510) th by thiscall pga) for matplti 01 sith afresh Python Trick code snippet every couple of days: Python Email Address >>> Import pandas 25 pd >>> import matplotib-eransforns 25 Send Python Tricks » b> unk = Inttps://feedsthoutsfed.or >>> WIK = pd.rebd_esv(url, Index col-6, parse dates-rrue, na_values-'.", squeeze-Truc)-aropna() 995 ma = vbs rottang( 900") reon() ooo ates pleats, bine-np. in, 8, 8, 28, e9.tne) labels ranee(4)) 29> emap = pe get_ena( Vion =") >os aa. plot(color-Toisek', Lineieth.s, wankers, Hastze-(8, Dy abel= "V2" 964 9") 333 an = placa) # Get the currant Ants that ma.plot() refarances >>> ax set abel) 95) ax set_ylabel(‘200 soving average: CAOE VDC") 23> pecgettésle( voasity Regine See") oo axentacrnse 555 ax Tegend(toe="upee” center") >> pecset xlinGamin-na index, xaneea.inéex-10) boo trans « mtnanafonss blondes transfora factory(ae tranbata, ax: transhxes) >>> for 4, color in ennerace(cnap([®.2, 8:4, 8.6, @.8))) a Fill between(na index, @ 1, where-staten-s, aceccloe=ctler, transfore-trans) ecavhline(vie.nean(), Linestyle=cishes", color cede 9" ‘Blphacb.6, 2bbel="Full-persed sean", markers") Volatility Regime State Soo ta =~ Fulkperiod mean 8 8 90 moving average: CBOE VIX 8 8 Pog gh PP ptt There's alothappening above: + nals 90-day moving average ofthe VIX Index, a measure of market expectations of near-term stock volatity states binning ofthe moving average into itferent regime states, high Vk is seen as signaling a heightened levelof earn the markerplace + enapis a ColorMap—a matplatlb object thats essentially 2 mapping of floats to RGBA colors. Any colormap can be reversed by appending "_r',50 Ravicn_r" isthe reversed Red Yellow. Green colormap. Matpotib maintains ‘handy visual reference guide to ColorMaps in its docs, + The only real pandas call we're making hee isra. plot) Tis cllsplt.piet() internally, soto integrate the abject oriented approach, we nced to get an explicit reference to the current Axes with ax = pit.geat) + The second chunk of ce creates © e.8) 5395, ColorMaps' spectrum.” ensneratet) sith afresh Improve Your Python et us an RGBA sequen 5} Python Trick code snippet every couple of days: Pandas also comes bultout with a smatt pe " theirown). However, all ofthese, ke the Email Address Wrapping Up ‘As shown by some ofthe examples abou. syntascheavy lbrary Creating a production-ready chart sometimes requires aha hour of Googling and combining a hodgepodge of lines in order to fine-tune a plot However, understanding how matpltlib’s interfaces interacts an investment that can pay off down the road. As Real Python's own Dan Bader has advise, aking the time to dissect code rather than resorting tothe Stack Overflow. “copy pasta” solution tends tobe a smarter long-term solution ticking to the object-oriented approach can save hours of rustration when you want to take a plot fom plan to a warkof at More Resources From the matplotib documentation: + Anindex of matplotlib examples + The usage FAQ + The tutorials page, which s broken up into beginner, intermediate, and advanced sections * Lifecycle ofa plot which touches on the object-oriented versus stateful approaches Free Bonus: Click hereto download 5 Python + Mat asa basis for making your own plots and graphics examples with full source code shat you can use Third-party esources: + atacamp's matpltlb cheat shoes + PLOS Computational Biology: Ten Simole Rules for Better Figures + Chapters (Plotting & Visualization) of Wes McKinney's Bython for Data Analysis, 2d ed. * Chaper 11 (visualization with Matplotlib, Pandas, and Seaborn) of Ted Petrou's Pandas Cookbook + Section 14 (Matplotlb: Potting) ofthe Sey Notes + Thesked color palette + The matplotib external resources page from queiroztcom + The sualization page_in the pandas documentation Other plotting libraries: ‘+ The seaborn library, bult ontop of matplotib and designed for advanced statistical graphics, which could take pan entire tutorial all on its own + atashader,a graphics library geared specifically towards large datasets + Alistof other third-party packages from the matplotit Fi Become a Python Expert » Appendix A: Configuration and Styling you've been following along with tis stylistically than the ones shown here ren lookcitferent torial, it's Ukely thatthe ph 9s popping up on your se Notpltibofers two ways to configures Improve Your Python 1 Bycustomizing a matplatire fle sith afresh Python Trick 2. By changing your configuration pars code snippet every couple of days ‘Amatpltibrcfile (Option #L above) isbs Emailaddress between Python sessions. On Mac OSX, ‘Quick Tip: GitHub isa great place tok contain personaly identifiable or private wiormaton, suchas passwords or 20m private nays ‘Atematively, you can change your configuration parameters interactively (Option #2 above). When you Seport ratplotlib.pyplot as plt, yOu get access to an rcParans abject that resembles a Python dictionary of settings Allof the module objects starting with rc" are a means tointeract with your plot styles and settings: >>> atte for atte in dirgolt) i at Ure startewith(re')] ‘earans', ‘"cParansbefaule”, “re_context", “redefaults*) ofthese: + put.redefeuite() restores there parameters from matplatibs internal defauits, which are listed at pit.reParanabefault This will vert (overurite) whatever you've already customizeé ina matplotibre file. + pit.ret) is used for setting parameters interactively + pit.reParans sa (mutable) dictionary.ike object that lets you manipulate settings directly. you have customized settings in a matplotibe file, these willbe reflected inthis dictionary With pit.re() andpls.reparan, these two syntaxes are equivalent for adjusting settings: Python = boo pltce( Mines’, Mnewen2, ot oy # satan do pt.echaran{'Lines.Linewidth'] = 2.4 Syntax 2 >> pltsneparanstLines-color') Notably, the Figure class then uses some of these as its default arguments. Relatedy, a style isjust a predefined of custom settings. To vew available styles, use: Python [eeatoredari'y“eeatorcdarkgria,‘eaborectiske', “hvethirgeeht dark bockgraund’, "seabor-poster", "sesborn-deep | . Toseta style, make this call >>> pt. style uset!svetnioreiahe') Your plots will now take on anew look: “fivethirtyeight’ style sheet » . on Improve Your Python sith afesh Bs Python Trek ao code snippetevery couple of days: 20 mall address This full example is available here. For inspiration, matplotlb keeps some style sheet displays for reference as well, A Learn Python » en) emo Appendix B: Interactive Mode Behind the scenes, matpltib also interacts wih diffrent backends. A backend’ the workhorse behind actually rendering a char. (On the popular Anaconda distribution, for instance, the default backend is QtSAgg) Some backenes are interactive, meaning they are dynamically updated and “pop up" tothe ser when changed While interactive mode i off by default, you can chec plt.ssincaractive(), and toggleiton and off with pls. sont) and pit. to##(), respectively ts status with p1t-reParans interactive") oF bo» pltneparans{"interactive"] a ort plt.sstnteractivet Python a bo» pt. 40FF0) doo pt ecbarna[ interactive") In some code examples, you may notice the presence of pit-stou() atthe end ofa chunk of code. The main purpose of pit.show(), asthe name implies, isto actualy “show” (open) the figure when you're running with interactive mode turned of n other wards + tfinterative mode is on, you don't need pit.shaw(),and images will automatically pop-up and be updated as youreferencethem, + Hfinterative modes off you'll need pit. show() to dlsplay a figure and pis.areu() to update a plot Below, we make sure that interactive mode is off, which requires that we call pit-shout) after building the plot ise: bee pit. 40f€0 >> pe plete, 7h e's Mnestyle='solie") >> ae HAL between, JL, 2, wheeryDyt, interpolates, olor prcsn'y alpha-6.3) 29> land = axlegend(C'yt', "72", loe~‘uppar center’, shadow-True) >>> gn. get_tave()-set_Facecolor( 8109") b> pt aha) Improve Your Python Notaby interactive oe has nothing to ) Python Trick 3 code snippet every couple of days: something ike juoyter notebook --naty sith afresh Email Address (CTD Tis tutoriat has a eater written tutorial to deepen your unders B python Tricks Geta short & sweet Python Trick delvere to your inbox every couple of ays. No spam ever. Unsubscribe anytime. Curated by the Real Python Email Address About Brad Solomon Bradisa software engineer and a member of the Real Python Tutorial Team >More about Brad ach tutorial at Real Python is created by a team of developers so that it meets our igh quality stondards. The team members who worked on tis tutorial are: E Master Real-World Python Skills With unl’ ~ Improve Your Python sith afesh Bs Python Trick ove snippet every couple of ay: dress Join us and get access to hundreds of tutorials, hands ‘on video courses, and a community of expert Pythonistas: What Do You Think? (ieee) (Fear) (tem) Real Python Comment Policy: The mast useful comments are those written with the goal of learning {rom or helping out other readers~after reading the whole article andall he earler comments. Complaints and insults generally won't make the cut here. Whats your#1 takeaway or favorite thing you learned? How are you going to put your newfound sills touse? Leave a comment below and letus know. Ins stpoystap ued, nme gud, your the nis stpy-stop ce 30 Comments Real Python Disqus’ Privacy Policy @ Lovin O Racamenend 24 sory Best Join the siscussion seam enstonsewmcncus @ Keep Learning Improve Your Python Related Tutorial Categories: (Baia) with a fresh 3 Python Trick code snippet every couple of days: Recommended Video Cours: Email Address mall (No spar. Unsubscribe anytime All Tutorial Topics

You might also like