_axes.py 325 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454
  1. import functools
  2. import itertools
  3. import logging
  4. import math
  5. from numbers import Integral, Number, Real
  6. import numpy as np
  7. from numpy import ma
  8. import matplotlib as mpl
  9. import matplotlib.category # Register category unit converter as side effect.
  10. import matplotlib.cbook as cbook
  11. import matplotlib.collections as mcoll
  12. import matplotlib.colors as mcolors
  13. import matplotlib.contour as mcontour
  14. import matplotlib.dates # noqa # Register date unit converter as side effect.
  15. import matplotlib.image as mimage
  16. import matplotlib.legend as mlegend
  17. import matplotlib.lines as mlines
  18. import matplotlib.markers as mmarkers
  19. import matplotlib.mlab as mlab
  20. import matplotlib.patches as mpatches
  21. import matplotlib.path as mpath
  22. import matplotlib.quiver as mquiver
  23. import matplotlib.stackplot as mstack
  24. import matplotlib.streamplot as mstream
  25. import matplotlib.table as mtable
  26. import matplotlib.text as mtext
  27. import matplotlib.ticker as mticker
  28. import matplotlib.transforms as mtransforms
  29. import matplotlib.tri as mtri
  30. import matplotlib.units as munits
  31. from matplotlib import _api, _docstring, _preprocess_data
  32. from matplotlib.axes._base import (
  33. _AxesBase, _TransformedBoundsLocator, _process_plot_format)
  34. from matplotlib.axes._secondary_axes import SecondaryAxis
  35. from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
  36. _log = logging.getLogger(__name__)
  37. # The axes module contains all the wrappers to plotting functions.
  38. # All the other methods should go in the _AxesBase class.
  39. @_docstring.interpd
  40. class Axes(_AxesBase):
  41. """
  42. An Axes object encapsulates all the elements of an individual (sub-)plot in
  43. a figure.
  44. It contains most of the (sub-)plot elements: `~.axis.Axis`,
  45. `~.axis.Tick`, `~.lines.Line2D`, `~.text.Text`, `~.patches.Polygon`, etc.,
  46. and sets the coordinate system.
  47. Like all visible elements in a figure, Axes is an `.Artist` subclass.
  48. The `Axes` instance supports callbacks through a callbacks attribute which
  49. is a `~.cbook.CallbackRegistry` instance. The events you can connect to
  50. are 'xlim_changed' and 'ylim_changed' and the callback will be called with
  51. func(*ax*) where *ax* is the `Axes` instance.
  52. .. note::
  53. As a user, you do not instantiate Axes directly, but use Axes creation
  54. methods instead; e.g. from `.pyplot` or `.Figure`:
  55. `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` or `.Figure.add_axes`.
  56. Attributes
  57. ----------
  58. dataLim : `.Bbox`
  59. The bounding box enclosing all data displayed in the Axes.
  60. viewLim : `.Bbox`
  61. The view limits in data coordinates.
  62. """
  63. ### Labelling, legend and texts
  64. def get_title(self, loc="center"):
  65. """
  66. Get an Axes title.
  67. Get one of the three available Axes titles. The available titles
  68. are positioned above the Axes in the center, flush with the left
  69. edge, and flush with the right edge.
  70. Parameters
  71. ----------
  72. loc : {'center', 'left', 'right'}, str, default: 'center'
  73. Which title to return.
  74. Returns
  75. -------
  76. str
  77. The title text string.
  78. """
  79. titles = {'left': self._left_title,
  80. 'center': self.title,
  81. 'right': self._right_title}
  82. title = _api.check_getitem(titles, loc=loc.lower())
  83. return title.get_text()
  84. def set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None,
  85. **kwargs):
  86. """
  87. Set a title for the Axes.
  88. Set one of the three available Axes titles. The available titles
  89. are positioned above the Axes in the center, flush with the left
  90. edge, and flush with the right edge.
  91. Parameters
  92. ----------
  93. label : str
  94. Text to use for the title
  95. fontdict : dict
  96. .. admonition:: Discouraged
  97. The use of *fontdict* is discouraged. Parameters should be passed as
  98. individual keyword arguments or using dictionary-unpacking
  99. ``set_title(..., **fontdict)``.
  100. A dictionary controlling the appearance of the title text,
  101. the default *fontdict* is::
  102. {'fontsize': rcParams['axes.titlesize'],
  103. 'fontweight': rcParams['axes.titleweight'],
  104. 'color': rcParams['axes.titlecolor'],
  105. 'verticalalignment': 'baseline',
  106. 'horizontalalignment': loc}
  107. loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation`
  108. Which title to set.
  109. y : float, default: :rc:`axes.titley`
  110. Vertical Axes location for the title (1.0 is the top). If
  111. None (the default) and :rc:`axes.titley` is also None, y is
  112. determined automatically to avoid decorators on the Axes.
  113. pad : float, default: :rc:`axes.titlepad`
  114. The offset of the title from the top of the Axes, in points.
  115. Returns
  116. -------
  117. `.Text`
  118. The matplotlib text instance representing the title
  119. Other Parameters
  120. ----------------
  121. **kwargs : `~matplotlib.text.Text` properties
  122. Other keyword arguments are text properties, see `.Text` for a list
  123. of valid text properties.
  124. """
  125. if loc is None:
  126. loc = mpl.rcParams['axes.titlelocation']
  127. if y is None:
  128. y = mpl.rcParams['axes.titley']
  129. if y is None:
  130. y = 1.0
  131. else:
  132. self._autotitlepos = False
  133. kwargs['y'] = y
  134. titles = {'left': self._left_title,
  135. 'center': self.title,
  136. 'right': self._right_title}
  137. title = _api.check_getitem(titles, loc=loc.lower())
  138. default = {
  139. 'fontsize': mpl.rcParams['axes.titlesize'],
  140. 'fontweight': mpl.rcParams['axes.titleweight'],
  141. 'verticalalignment': 'baseline',
  142. 'horizontalalignment': loc.lower()}
  143. titlecolor = mpl.rcParams['axes.titlecolor']
  144. if not cbook._str_lower_equal(titlecolor, 'auto'):
  145. default["color"] = titlecolor
  146. if pad is None:
  147. pad = mpl.rcParams['axes.titlepad']
  148. self._set_title_offset_trans(float(pad))
  149. title.set_text(label)
  150. title.update(default)
  151. if fontdict is not None:
  152. title.update(fontdict)
  153. title._internal_update(kwargs)
  154. return title
  155. def get_legend_handles_labels(self, legend_handler_map=None):
  156. """
  157. Return handles and labels for legend
  158. ``ax.legend()`` is equivalent to ::
  159. h, l = ax.get_legend_handles_labels()
  160. ax.legend(h, l)
  161. """
  162. # pass through to legend.
  163. handles, labels = mlegend._get_legend_handles_labels(
  164. [self], legend_handler_map)
  165. return handles, labels
  166. @_docstring.dedent_interpd
  167. def legend(self, *args, **kwargs):
  168. """
  169. Place a legend on the Axes.
  170. Call signatures::
  171. legend()
  172. legend(handles, labels)
  173. legend(handles=handles)
  174. legend(labels)
  175. The call signatures correspond to the following different ways to use
  176. this method:
  177. **1. Automatic detection of elements to be shown in the legend**
  178. The elements to be added to the legend are automatically determined,
  179. when you do not pass in any extra arguments.
  180. In this case, the labels are taken from the artist. You can specify
  181. them either at artist creation or by calling the
  182. :meth:`~.Artist.set_label` method on the artist::
  183. ax.plot([1, 2, 3], label='Inline label')
  184. ax.legend()
  185. or::
  186. line, = ax.plot([1, 2, 3])
  187. line.set_label('Label via method')
  188. ax.legend()
  189. .. note::
  190. Specific artists can be excluded from the automatic legend element
  191. selection by using a label starting with an underscore, "_".
  192. A string starting with an underscore is the default label for all
  193. artists, so calling `.Axes.legend` without any arguments and
  194. without setting the labels manually will result in no legend being
  195. drawn.
  196. **2. Explicitly listing the artists and labels in the legend**
  197. For full control of which artists have a legend entry, it is possible
  198. to pass an iterable of legend artists followed by an iterable of
  199. legend labels respectively::
  200. ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
  201. **3. Explicitly listing the artists in the legend**
  202. This is similar to 2, but the labels are taken from the artists'
  203. label properties. Example::
  204. line1, = ax.plot([1, 2, 3], label='label1')
  205. line2, = ax.plot([1, 2, 3], label='label2')
  206. ax.legend(handles=[line1, line2])
  207. **4. Labeling existing plot elements**
  208. .. admonition:: Discouraged
  209. This call signature is discouraged, because the relation between
  210. plot elements and labels is only implicit by their order and can
  211. easily be mixed up.
  212. To make a legend for all artists on an Axes, call this function with
  213. an iterable of strings, one for each legend item. For example::
  214. ax.plot([1, 2, 3])
  215. ax.plot([5, 6, 7])
  216. ax.legend(['First line', 'Second line'])
  217. Parameters
  218. ----------
  219. handles : sequence of (`.Artist` or tuple of `.Artist`), optional
  220. A list of Artists (lines, patches) to be added to the legend.
  221. Use this together with *labels*, if you need full control on what
  222. is shown in the legend and the automatic mechanism described above
  223. is not sufficient.
  224. The length of handles and labels should be the same in this
  225. case. If they are not, they are truncated to the smaller length.
  226. If an entry contains a tuple, then the legend handler for all Artists in the
  227. tuple will be placed alongside a single label.
  228. labels : list of str, optional
  229. A list of labels to show next to the artists.
  230. Use this together with *handles*, if you need full control on what
  231. is shown in the legend and the automatic mechanism described above
  232. is not sufficient.
  233. Returns
  234. -------
  235. `~matplotlib.legend.Legend`
  236. Other Parameters
  237. ----------------
  238. %(_legend_kw_axes)s
  239. See Also
  240. --------
  241. .Figure.legend
  242. Notes
  243. -----
  244. Some artists are not supported by this function. See
  245. :ref:`legend_guide` for details.
  246. Examples
  247. --------
  248. .. plot:: gallery/text_labels_and_annotations/legend.py
  249. """
  250. handles, labels, kwargs = mlegend._parse_legend_args([self], *args, **kwargs)
  251. self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
  252. self.legend_._remove_method = self._remove_legend
  253. return self.legend_
  254. def _remove_legend(self, legend):
  255. self.legend_ = None
  256. def inset_axes(self, bounds, *, transform=None, zorder=5, **kwargs):
  257. """
  258. Add a child inset Axes to this existing Axes.
  259. Warnings
  260. --------
  261. This method is experimental as of 3.0, and the API may change.
  262. Parameters
  263. ----------
  264. bounds : [x0, y0, width, height]
  265. Lower-left corner of inset Axes, and its width and height.
  266. transform : `.Transform`
  267. Defaults to `ax.transAxes`, i.e. the units of *rect* are in
  268. Axes-relative coordinates.
  269. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
  270. 'polar', 'rectilinear', str}, optional
  271. The projection type of the inset `~.axes.Axes`. *str* is the name
  272. of a custom projection, see `~matplotlib.projections`. The default
  273. None results in a 'rectilinear' projection.
  274. polar : bool, default: False
  275. If True, equivalent to projection='polar'.
  276. axes_class : subclass type of `~.axes.Axes`, optional
  277. The `.axes.Axes` subclass that is instantiated. This parameter
  278. is incompatible with *projection* and *polar*. See
  279. :ref:`axisartist_users-guide-index` for examples.
  280. zorder : number
  281. Defaults to 5 (same as `.Axes.legend`). Adjust higher or lower
  282. to change whether it is above or below data plotted on the
  283. parent Axes.
  284. **kwargs
  285. Other keyword arguments are passed on to the inset Axes class.
  286. Returns
  287. -------
  288. ax
  289. The created `~.axes.Axes` instance.
  290. Examples
  291. --------
  292. This example makes two inset Axes, the first is in Axes-relative
  293. coordinates, and the second in data-coordinates::
  294. fig, ax = plt.subplots()
  295. ax.plot(range(10))
  296. axin1 = ax.inset_axes([0.8, 0.1, 0.15, 0.15])
  297. axin2 = ax.inset_axes(
  298. [5, 7, 2.3, 2.3], transform=ax.transData)
  299. """
  300. if transform is None:
  301. transform = self.transAxes
  302. kwargs.setdefault('label', 'inset_axes')
  303. # This puts the rectangle into figure-relative coordinates.
  304. inset_locator = _TransformedBoundsLocator(bounds, transform)
  305. bounds = inset_locator(self, None).bounds
  306. projection_class, pkw = self.figure._process_projection_requirements(**kwargs)
  307. inset_ax = projection_class(self.figure, bounds, zorder=zorder, **pkw)
  308. # this locator lets the axes move if in data coordinates.
  309. # it gets called in `ax.apply_aspect() (of all places)
  310. inset_ax.set_axes_locator(inset_locator)
  311. self.add_child_axes(inset_ax)
  312. return inset_ax
  313. @_docstring.dedent_interpd
  314. def indicate_inset(self, bounds, inset_ax=None, *, transform=None,
  315. facecolor='none', edgecolor='0.5', alpha=0.5,
  316. zorder=4.99, **kwargs):
  317. """
  318. Add an inset indicator to the Axes. This is a rectangle on the plot
  319. at the position indicated by *bounds* that optionally has lines that
  320. connect the rectangle to an inset Axes (`.Axes.inset_axes`).
  321. Warnings
  322. --------
  323. This method is experimental as of 3.0, and the API may change.
  324. Parameters
  325. ----------
  326. bounds : [x0, y0, width, height]
  327. Lower-left corner of rectangle to be marked, and its width
  328. and height.
  329. inset_ax : `.Axes`
  330. An optional inset Axes to draw connecting lines to. Two lines are
  331. drawn connecting the indicator box to the inset Axes on corners
  332. chosen so as to not overlap with the indicator box.
  333. transform : `.Transform`
  334. Transform for the rectangle coordinates. Defaults to
  335. `ax.transAxes`, i.e. the units of *rect* are in Axes-relative
  336. coordinates.
  337. facecolor : color, default: 'none'
  338. Facecolor of the rectangle.
  339. edgecolor : color, default: '0.5'
  340. Color of the rectangle and color of the connecting lines.
  341. alpha : float, default: 0.5
  342. Transparency of the rectangle and connector lines.
  343. zorder : float, default: 4.99
  344. Drawing order of the rectangle and connector lines. The default,
  345. 4.99, is just below the default level of inset Axes.
  346. **kwargs
  347. Other keyword arguments are passed on to the `.Rectangle` patch:
  348. %(Rectangle:kwdoc)s
  349. Returns
  350. -------
  351. rectangle_patch : `.patches.Rectangle`
  352. The indicator frame.
  353. connector_lines : 4-tuple of `.patches.ConnectionPatch`
  354. The four connector lines connecting to (lower_left, upper_left,
  355. lower_right upper_right) corners of *inset_ax*. Two lines are
  356. set with visibility to *False*, but the user can set the
  357. visibility to True if the automatic choice is not deemed correct.
  358. """
  359. # to make the axes connectors work, we need to apply the aspect to
  360. # the parent axes.
  361. self.apply_aspect()
  362. if transform is None:
  363. transform = self.transData
  364. kwargs.setdefault('label', '_indicate_inset')
  365. x, y, width, height = bounds
  366. rectangle_patch = mpatches.Rectangle(
  367. (x, y), width, height,
  368. facecolor=facecolor, edgecolor=edgecolor, alpha=alpha,
  369. zorder=zorder, transform=transform, **kwargs)
  370. self.add_patch(rectangle_patch)
  371. connects = []
  372. if inset_ax is not None:
  373. # connect the inset_axes to the rectangle
  374. for xy_inset_ax in [(0, 0), (0, 1), (1, 0), (1, 1)]:
  375. # inset_ax positions are in axes coordinates
  376. # The 0, 1 values define the four edges if the inset_ax
  377. # lower_left, upper_left, lower_right upper_right.
  378. ex, ey = xy_inset_ax
  379. if self.xaxis.get_inverted():
  380. ex = 1 - ex
  381. if self.yaxis.get_inverted():
  382. ey = 1 - ey
  383. xy_data = x + ex * width, y + ey * height
  384. p = mpatches.ConnectionPatch(
  385. xyA=xy_inset_ax, coordsA=inset_ax.transAxes,
  386. xyB=xy_data, coordsB=self.transData,
  387. arrowstyle="-", zorder=zorder,
  388. edgecolor=edgecolor, alpha=alpha)
  389. connects.append(p)
  390. self.add_patch(p)
  391. # decide which two of the lines to keep visible....
  392. pos = inset_ax.get_position()
  393. bboxins = pos.transformed(self.figure.transSubfigure)
  394. rectbbox = mtransforms.Bbox.from_bounds(
  395. *bounds
  396. ).transformed(transform)
  397. x0 = rectbbox.x0 < bboxins.x0
  398. x1 = rectbbox.x1 < bboxins.x1
  399. y0 = rectbbox.y0 < bboxins.y0
  400. y1 = rectbbox.y1 < bboxins.y1
  401. connects[0].set_visible(x0 ^ y0)
  402. connects[1].set_visible(x0 == y1)
  403. connects[2].set_visible(x1 == y0)
  404. connects[3].set_visible(x1 ^ y1)
  405. return rectangle_patch, tuple(connects) if connects else None
  406. def indicate_inset_zoom(self, inset_ax, **kwargs):
  407. """
  408. Add an inset indicator rectangle to the Axes based on the axis
  409. limits for an *inset_ax* and draw connectors between *inset_ax*
  410. and the rectangle.
  411. Warnings
  412. --------
  413. This method is experimental as of 3.0, and the API may change.
  414. Parameters
  415. ----------
  416. inset_ax : `.Axes`
  417. Inset Axes to draw connecting lines to. Two lines are
  418. drawn connecting the indicator box to the inset Axes on corners
  419. chosen so as to not overlap with the indicator box.
  420. **kwargs
  421. Other keyword arguments are passed on to `.Axes.indicate_inset`
  422. Returns
  423. -------
  424. rectangle_patch : `.patches.Rectangle`
  425. Rectangle artist.
  426. connector_lines : 4-tuple of `.patches.ConnectionPatch`
  427. Each of four connector lines coming from the rectangle drawn on
  428. this axis, in the order lower left, upper left, lower right,
  429. upper right.
  430. Two are set with visibility to *False*, but the user can
  431. set the visibility to *True* if the automatic choice is not deemed
  432. correct.
  433. """
  434. xlim = inset_ax.get_xlim()
  435. ylim = inset_ax.get_ylim()
  436. rect = (xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0])
  437. return self.indicate_inset(rect, inset_ax, **kwargs)
  438. @_docstring.dedent_interpd
  439. def secondary_xaxis(self, location, *, functions=None, **kwargs):
  440. """
  441. Add a second x-axis to this `~.axes.Axes`.
  442. For example if we want to have a second scale for the data plotted on
  443. the xaxis.
  444. %(_secax_docstring)s
  445. Examples
  446. --------
  447. The main axis shows frequency, and the secondary axis shows period.
  448. .. plot::
  449. fig, ax = plt.subplots()
  450. ax.loglog(range(1, 360, 5), range(1, 360, 5))
  451. ax.set_xlabel('frequency [Hz]')
  452. def invert(x):
  453. # 1/x with special treatment of x == 0
  454. x = np.array(x).astype(float)
  455. near_zero = np.isclose(x, 0)
  456. x[near_zero] = np.inf
  457. x[~near_zero] = 1 / x[~near_zero]
  458. return x
  459. # the inverse of 1/x is itself
  460. secax = ax.secondary_xaxis('top', functions=(invert, invert))
  461. secax.set_xlabel('Period [s]')
  462. plt.show()
  463. """
  464. if location in ['top', 'bottom'] or isinstance(location, Real):
  465. secondary_ax = SecondaryAxis(self, 'x', location, functions,
  466. **kwargs)
  467. self.add_child_axes(secondary_ax)
  468. return secondary_ax
  469. else:
  470. raise ValueError('secondary_xaxis location must be either '
  471. 'a float or "top"/"bottom"')
  472. @_docstring.dedent_interpd
  473. def secondary_yaxis(self, location, *, functions=None, **kwargs):
  474. """
  475. Add a second y-axis to this `~.axes.Axes`.
  476. For example if we want to have a second scale for the data plotted on
  477. the yaxis.
  478. %(_secax_docstring)s
  479. Examples
  480. --------
  481. Add a secondary Axes that converts from radians to degrees
  482. .. plot::
  483. fig, ax = plt.subplots()
  484. ax.plot(range(1, 360, 5), range(1, 360, 5))
  485. ax.set_ylabel('degrees')
  486. secax = ax.secondary_yaxis('right', functions=(np.deg2rad,
  487. np.rad2deg))
  488. secax.set_ylabel('radians')
  489. """
  490. if location in ['left', 'right'] or isinstance(location, Real):
  491. secondary_ax = SecondaryAxis(self, 'y', location,
  492. functions, **kwargs)
  493. self.add_child_axes(secondary_ax)
  494. return secondary_ax
  495. else:
  496. raise ValueError('secondary_yaxis location must be either '
  497. 'a float or "left"/"right"')
  498. @_docstring.dedent_interpd
  499. def text(self, x, y, s, fontdict=None, **kwargs):
  500. """
  501. Add text to the Axes.
  502. Add the text *s* to the Axes at location *x*, *y* in data coordinates.
  503. Parameters
  504. ----------
  505. x, y : float
  506. The position to place the text. By default, this is in data
  507. coordinates. The coordinate system can be changed using the
  508. *transform* parameter.
  509. s : str
  510. The text.
  511. fontdict : dict, default: None
  512. .. admonition:: Discouraged
  513. The use of *fontdict* is discouraged. Parameters should be passed as
  514. individual keyword arguments or using dictionary-unpacking
  515. ``text(..., **fontdict)``.
  516. A dictionary to override the default text properties. If fontdict
  517. is None, the defaults are determined by `.rcParams`.
  518. Returns
  519. -------
  520. `.Text`
  521. The created `.Text` instance.
  522. Other Parameters
  523. ----------------
  524. **kwargs : `~matplotlib.text.Text` properties.
  525. Other miscellaneous text parameters.
  526. %(Text:kwdoc)s
  527. Examples
  528. --------
  529. Individual keyword arguments can be used to override any given
  530. parameter::
  531. >>> text(x, y, s, fontsize=12)
  532. The default transform specifies that text is in data coords,
  533. alternatively, you can specify text in axis coords ((0, 0) is
  534. lower-left and (1, 1) is upper-right). The example below places
  535. text in the center of the Axes::
  536. >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
  537. ... verticalalignment='center', transform=ax.transAxes)
  538. You can put a rectangular box around the text instance (e.g., to
  539. set a background color) by using the keyword *bbox*. *bbox* is
  540. a dictionary of `~matplotlib.patches.Rectangle`
  541. properties. For example::
  542. >>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
  543. """
  544. effective_kwargs = {
  545. 'verticalalignment': 'baseline',
  546. 'horizontalalignment': 'left',
  547. 'transform': self.transData,
  548. 'clip_on': False,
  549. **(fontdict if fontdict is not None else {}),
  550. **kwargs,
  551. }
  552. t = mtext.Text(x, y, text=s, **effective_kwargs)
  553. if t.get_clip_path() is None:
  554. t.set_clip_path(self.patch)
  555. self._add_text(t)
  556. return t
  557. @_docstring.dedent_interpd
  558. def annotate(self, text, xy, xytext=None, xycoords='data', textcoords=None,
  559. arrowprops=None, annotation_clip=None, **kwargs):
  560. # Signature must match Annotation. This is verified in
  561. # test_annotate_signature().
  562. a = mtext.Annotation(text, xy, xytext=xytext, xycoords=xycoords,
  563. textcoords=textcoords, arrowprops=arrowprops,
  564. annotation_clip=annotation_clip, **kwargs)
  565. a.set_transform(mtransforms.IdentityTransform())
  566. if kwargs.get('clip_on', False) and a.get_clip_path() is None:
  567. a.set_clip_path(self.patch)
  568. self._add_text(a)
  569. return a
  570. annotate.__doc__ = mtext.Annotation.__init__.__doc__
  571. #### Lines and spans
  572. @_docstring.dedent_interpd
  573. def axhline(self, y=0, xmin=0, xmax=1, **kwargs):
  574. """
  575. Add a horizontal line across the Axes.
  576. Parameters
  577. ----------
  578. y : float, default: 0
  579. y position in data coordinates of the horizontal line.
  580. xmin : float, default: 0
  581. Should be between 0 and 1, 0 being the far left of the plot, 1 the
  582. far right of the plot.
  583. xmax : float, default: 1
  584. Should be between 0 and 1, 0 being the far left of the plot, 1 the
  585. far right of the plot.
  586. Returns
  587. -------
  588. `~matplotlib.lines.Line2D`
  589. Other Parameters
  590. ----------------
  591. **kwargs
  592. Valid keyword arguments are `.Line2D` properties, except for
  593. 'transform':
  594. %(Line2D:kwdoc)s
  595. See Also
  596. --------
  597. hlines : Add horizontal lines in data coordinates.
  598. axhspan : Add a horizontal span (rectangle) across the axis.
  599. axline : Add a line with an arbitrary slope.
  600. Examples
  601. --------
  602. * draw a thick red hline at 'y' = 0 that spans the xrange::
  603. >>> axhline(linewidth=4, color='r')
  604. * draw a default hline at 'y' = 1 that spans the xrange::
  605. >>> axhline(y=1)
  606. * draw a default hline at 'y' = .5 that spans the middle half of
  607. the xrange::
  608. >>> axhline(y=.5, xmin=0.25, xmax=0.75)
  609. """
  610. self._check_no_units([xmin, xmax], ['xmin', 'xmax'])
  611. if "transform" in kwargs:
  612. raise ValueError("'transform' is not allowed as a keyword "
  613. "argument; axhline generates its own transform.")
  614. ymin, ymax = self.get_ybound()
  615. # Strip away the units for comparison with non-unitized bounds.
  616. yy, = self._process_unit_info([("y", y)], kwargs)
  617. scaley = (yy < ymin) or (yy > ymax)
  618. trans = self.get_yaxis_transform(which='grid')
  619. l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs)
  620. self.add_line(l)
  621. if scaley:
  622. self._request_autoscale_view("y")
  623. return l
  624. @_docstring.dedent_interpd
  625. def axvline(self, x=0, ymin=0, ymax=1, **kwargs):
  626. """
  627. Add a vertical line across the Axes.
  628. Parameters
  629. ----------
  630. x : float, default: 0
  631. x position in data coordinates of the vertical line.
  632. ymin : float, default: 0
  633. Should be between 0 and 1, 0 being the bottom of the plot, 1 the
  634. top of the plot.
  635. ymax : float, default: 1
  636. Should be between 0 and 1, 0 being the bottom of the plot, 1 the
  637. top of the plot.
  638. Returns
  639. -------
  640. `~matplotlib.lines.Line2D`
  641. Other Parameters
  642. ----------------
  643. **kwargs
  644. Valid keyword arguments are `.Line2D` properties, except for
  645. 'transform':
  646. %(Line2D:kwdoc)s
  647. See Also
  648. --------
  649. vlines : Add vertical lines in data coordinates.
  650. axvspan : Add a vertical span (rectangle) across the axis.
  651. axline : Add a line with an arbitrary slope.
  652. Examples
  653. --------
  654. * draw a thick red vline at *x* = 0 that spans the yrange::
  655. >>> axvline(linewidth=4, color='r')
  656. * draw a default vline at *x* = 1 that spans the yrange::
  657. >>> axvline(x=1)
  658. * draw a default vline at *x* = .5 that spans the middle half of
  659. the yrange::
  660. >>> axvline(x=.5, ymin=0.25, ymax=0.75)
  661. """
  662. self._check_no_units([ymin, ymax], ['ymin', 'ymax'])
  663. if "transform" in kwargs:
  664. raise ValueError("'transform' is not allowed as a keyword "
  665. "argument; axvline generates its own transform.")
  666. xmin, xmax = self.get_xbound()
  667. # Strip away the units for comparison with non-unitized bounds.
  668. xx, = self._process_unit_info([("x", x)], kwargs)
  669. scalex = (xx < xmin) or (xx > xmax)
  670. trans = self.get_xaxis_transform(which='grid')
  671. l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs)
  672. self.add_line(l)
  673. if scalex:
  674. self._request_autoscale_view("x")
  675. return l
  676. @staticmethod
  677. def _check_no_units(vals, names):
  678. # Helper method to check that vals are not unitized
  679. for val, name in zip(vals, names):
  680. if not munits._is_natively_supported(val):
  681. raise ValueError(f"{name} must be a single scalar value, "
  682. f"but got {val}")
  683. @_docstring.dedent_interpd
  684. def axline(self, xy1, xy2=None, *, slope=None, **kwargs):
  685. """
  686. Add an infinitely long straight line.
  687. The line can be defined either by two points *xy1* and *xy2*, or
  688. by one point *xy1* and a *slope*.
  689. This draws a straight line "on the screen", regardless of the x and y
  690. scales, and is thus also suitable for drawing exponential decays in
  691. semilog plots, power laws in loglog plots, etc. However, *slope*
  692. should only be used with linear scales; It has no clear meaning for
  693. all other scales, and thus the behavior is undefined. Please specify
  694. the line using the points *xy1*, *xy2* for non-linear scales.
  695. The *transform* keyword argument only applies to the points *xy1*,
  696. *xy2*. The *slope* (if given) is always in data coordinates. This can
  697. be used e.g. with ``ax.transAxes`` for drawing grid lines with a fixed
  698. slope.
  699. Parameters
  700. ----------
  701. xy1, xy2 : (float, float)
  702. Points for the line to pass through.
  703. Either *xy2* or *slope* has to be given.
  704. slope : float, optional
  705. The slope of the line. Either *xy2* or *slope* has to be given.
  706. Returns
  707. -------
  708. `.Line2D`
  709. Other Parameters
  710. ----------------
  711. **kwargs
  712. Valid kwargs are `.Line2D` properties
  713. %(Line2D:kwdoc)s
  714. See Also
  715. --------
  716. axhline : for horizontal lines
  717. axvline : for vertical lines
  718. Examples
  719. --------
  720. Draw a thick red line passing through (0, 0) and (1, 1)::
  721. >>> axline((0, 0), (1, 1), linewidth=4, color='r')
  722. """
  723. if slope is not None and (self.get_xscale() != 'linear' or
  724. self.get_yscale() != 'linear'):
  725. raise TypeError("'slope' cannot be used with non-linear scales")
  726. datalim = [xy1] if xy2 is None else [xy1, xy2]
  727. if "transform" in kwargs:
  728. # if a transform is passed (i.e. line points not in data space),
  729. # data limits should not be adjusted.
  730. datalim = []
  731. line = mlines.AxLine(xy1, xy2, slope, **kwargs)
  732. # Like add_line, but correctly handling data limits.
  733. self._set_artist_props(line)
  734. if line.get_clip_path() is None:
  735. line.set_clip_path(self.patch)
  736. if not line.get_label():
  737. line.set_label(f"_child{len(self._children)}")
  738. self._children.append(line)
  739. line._remove_method = self._children.remove
  740. self.update_datalim(datalim)
  741. self._request_autoscale_view()
  742. return line
  743. @_docstring.dedent_interpd
  744. def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):
  745. """
  746. Add a horizontal span (rectangle) across the Axes.
  747. The rectangle spans from *ymin* to *ymax* vertically, and, by default,
  748. the whole x-axis horizontally. The x-span can be set using *xmin*
  749. (default: 0) and *xmax* (default: 1) which are in axis units; e.g.
  750. ``xmin = 0.5`` always refers to the middle of the x-axis regardless of
  751. the limits set by `~.Axes.set_xlim`.
  752. Parameters
  753. ----------
  754. ymin : float
  755. Lower y-coordinate of the span, in data units.
  756. ymax : float
  757. Upper y-coordinate of the span, in data units.
  758. xmin : float, default: 0
  759. Lower x-coordinate of the span, in x-axis (0-1) units.
  760. xmax : float, default: 1
  761. Upper x-coordinate of the span, in x-axis (0-1) units.
  762. Returns
  763. -------
  764. `~matplotlib.patches.Polygon`
  765. Horizontal span (rectangle) from (xmin, ymin) to (xmax, ymax).
  766. Other Parameters
  767. ----------------
  768. **kwargs : `~matplotlib.patches.Polygon` properties
  769. %(Polygon:kwdoc)s
  770. See Also
  771. --------
  772. axvspan : Add a vertical span across the Axes.
  773. """
  774. # Strip units away.
  775. self._check_no_units([xmin, xmax], ['xmin', 'xmax'])
  776. (ymin, ymax), = self._process_unit_info([("y", [ymin, ymax])], kwargs)
  777. verts = (xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)
  778. p = mpatches.Polygon(verts, **kwargs)
  779. p.set_transform(self.get_yaxis_transform(which="grid"))
  780. self.add_patch(p)
  781. self._request_autoscale_view("y")
  782. return p
  783. @_docstring.dedent_interpd
  784. def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):
  785. """
  786. Add a vertical span (rectangle) across the Axes.
  787. The rectangle spans from *xmin* to *xmax* horizontally, and, by
  788. default, the whole y-axis vertically. The y-span can be set using
  789. *ymin* (default: 0) and *ymax* (default: 1) which are in axis units;
  790. e.g. ``ymin = 0.5`` always refers to the middle of the y-axis
  791. regardless of the limits set by `~.Axes.set_ylim`.
  792. Parameters
  793. ----------
  794. xmin : float
  795. Lower x-coordinate of the span, in data units.
  796. xmax : float
  797. Upper x-coordinate of the span, in data units.
  798. ymin : float, default: 0
  799. Lower y-coordinate of the span, in y-axis units (0-1).
  800. ymax : float, default: 1
  801. Upper y-coordinate of the span, in y-axis units (0-1).
  802. Returns
  803. -------
  804. `~matplotlib.patches.Polygon`
  805. Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax).
  806. Other Parameters
  807. ----------------
  808. **kwargs : `~matplotlib.patches.Polygon` properties
  809. %(Polygon:kwdoc)s
  810. See Also
  811. --------
  812. axhspan : Add a horizontal span across the Axes.
  813. Examples
  814. --------
  815. Draw a vertical, green, translucent rectangle from x = 1.25 to
  816. x = 1.55 that spans the yrange of the Axes.
  817. >>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
  818. """
  819. # Strip units away.
  820. self._check_no_units([ymin, ymax], ['ymin', 'ymax'])
  821. (xmin, xmax), = self._process_unit_info([("x", [xmin, xmax])], kwargs)
  822. verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]
  823. p = mpatches.Polygon(verts, **kwargs)
  824. p.set_transform(self.get_xaxis_transform(which="grid"))
  825. p.get_path()._interpolation_steps = 100
  826. self.add_patch(p)
  827. self._request_autoscale_view("x")
  828. return p
  829. @_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"],
  830. label_namer="y")
  831. def hlines(self, y, xmin, xmax, colors=None, linestyles='solid',
  832. label='', **kwargs):
  833. """
  834. Plot horizontal lines at each *y* from *xmin* to *xmax*.
  835. Parameters
  836. ----------
  837. y : float or array-like
  838. y-indexes where to plot the lines.
  839. xmin, xmax : float or array-like
  840. Respective beginning and end of each line. If scalars are
  841. provided, all lines will have the same length.
  842. colors : color or list of colors, default: :rc:`lines.color`
  843. linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid'
  844. label : str, default: ''
  845. Returns
  846. -------
  847. `~matplotlib.collections.LineCollection`
  848. Other Parameters
  849. ----------------
  850. data : indexable object, optional
  851. DATA_PARAMETER_PLACEHOLDER
  852. **kwargs : `~matplotlib.collections.LineCollection` properties.
  853. See Also
  854. --------
  855. vlines : vertical lines
  856. axhline : horizontal line across the Axes
  857. """
  858. # We do the conversion first since not all unitized data is uniform
  859. xmin, xmax, y = self._process_unit_info(
  860. [("x", xmin), ("x", xmax), ("y", y)], kwargs)
  861. if not np.iterable(y):
  862. y = [y]
  863. if not np.iterable(xmin):
  864. xmin = [xmin]
  865. if not np.iterable(xmax):
  866. xmax = [xmax]
  867. # Create and combine masked_arrays from input
  868. y, xmin, xmax = cbook._combine_masks(y, xmin, xmax)
  869. y = np.ravel(y)
  870. xmin = np.ravel(xmin)
  871. xmax = np.ravel(xmax)
  872. masked_verts = np.ma.empty((len(y), 2, 2))
  873. masked_verts[:, 0, 0] = xmin
  874. masked_verts[:, 0, 1] = y
  875. masked_verts[:, 1, 0] = xmax
  876. masked_verts[:, 1, 1] = y
  877. lines = mcoll.LineCollection(masked_verts, colors=colors,
  878. linestyles=linestyles, label=label)
  879. self.add_collection(lines, autolim=False)
  880. lines._internal_update(kwargs)
  881. if len(y) > 0:
  882. # Extreme values of xmin/xmax/y. Using masked_verts here handles
  883. # the case of y being a masked *object* array (as can be generated
  884. # e.g. by errorbar()), which would make nanmin/nanmax stumble.
  885. updatex = True
  886. updatey = True
  887. if self.name == "rectilinear":
  888. datalim = lines.get_datalim(self.transData)
  889. t = lines.get_transform()
  890. updatex, updatey = t.contains_branch_seperately(self.transData)
  891. minx = np.nanmin(datalim.xmin)
  892. maxx = np.nanmax(datalim.xmax)
  893. miny = np.nanmin(datalim.ymin)
  894. maxy = np.nanmax(datalim.ymax)
  895. else:
  896. minx = np.nanmin(masked_verts[..., 0])
  897. maxx = np.nanmax(masked_verts[..., 0])
  898. miny = np.nanmin(masked_verts[..., 1])
  899. maxy = np.nanmax(masked_verts[..., 1])
  900. corners = (minx, miny), (maxx, maxy)
  901. self.update_datalim(corners, updatex, updatey)
  902. self._request_autoscale_view()
  903. return lines
  904. @_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"],
  905. label_namer="x")
  906. def vlines(self, x, ymin, ymax, colors=None, linestyles='solid',
  907. label='', **kwargs):
  908. """
  909. Plot vertical lines at each *x* from *ymin* to *ymax*.
  910. Parameters
  911. ----------
  912. x : float or array-like
  913. x-indexes where to plot the lines.
  914. ymin, ymax : float or array-like
  915. Respective beginning and end of each line. If scalars are
  916. provided, all lines will have the same length.
  917. colors : color or list of colors, default: :rc:`lines.color`
  918. linestyles : {'solid', 'dashed', 'dashdot', 'dotted'}, default: 'solid'
  919. label : str, default: ''
  920. Returns
  921. -------
  922. `~matplotlib.collections.LineCollection`
  923. Other Parameters
  924. ----------------
  925. data : indexable object, optional
  926. DATA_PARAMETER_PLACEHOLDER
  927. **kwargs : `~matplotlib.collections.LineCollection` properties.
  928. See Also
  929. --------
  930. hlines : horizontal lines
  931. axvline : vertical line across the Axes
  932. """
  933. # We do the conversion first since not all unitized data is uniform
  934. x, ymin, ymax = self._process_unit_info(
  935. [("x", x), ("y", ymin), ("y", ymax)], kwargs)
  936. if not np.iterable(x):
  937. x = [x]
  938. if not np.iterable(ymin):
  939. ymin = [ymin]
  940. if not np.iterable(ymax):
  941. ymax = [ymax]
  942. # Create and combine masked_arrays from input
  943. x, ymin, ymax = cbook._combine_masks(x, ymin, ymax)
  944. x = np.ravel(x)
  945. ymin = np.ravel(ymin)
  946. ymax = np.ravel(ymax)
  947. masked_verts = np.ma.empty((len(x), 2, 2))
  948. masked_verts[:, 0, 0] = x
  949. masked_verts[:, 0, 1] = ymin
  950. masked_verts[:, 1, 0] = x
  951. masked_verts[:, 1, 1] = ymax
  952. lines = mcoll.LineCollection(masked_verts, colors=colors,
  953. linestyles=linestyles, label=label)
  954. self.add_collection(lines, autolim=False)
  955. lines._internal_update(kwargs)
  956. if len(x) > 0:
  957. # Extreme values of x/ymin/ymax. Using masked_verts here handles
  958. # the case of x being a masked *object* array (as can be generated
  959. # e.g. by errorbar()), which would make nanmin/nanmax stumble.
  960. updatex = True
  961. updatey = True
  962. if self.name == "rectilinear":
  963. datalim = lines.get_datalim(self.transData)
  964. t = lines.get_transform()
  965. updatex, updatey = t.contains_branch_seperately(self.transData)
  966. minx = np.nanmin(datalim.xmin)
  967. maxx = np.nanmax(datalim.xmax)
  968. miny = np.nanmin(datalim.ymin)
  969. maxy = np.nanmax(datalim.ymax)
  970. else:
  971. minx = np.nanmin(masked_verts[..., 0])
  972. maxx = np.nanmax(masked_verts[..., 0])
  973. miny = np.nanmin(masked_verts[..., 1])
  974. maxy = np.nanmax(masked_verts[..., 1])
  975. corners = (minx, miny), (maxx, maxy)
  976. self.update_datalim(corners, updatex, updatey)
  977. self._request_autoscale_view()
  978. return lines
  979. @_preprocess_data(replace_names=["positions", "lineoffsets",
  980. "linelengths", "linewidths",
  981. "colors", "linestyles"])
  982. @_docstring.dedent_interpd
  983. def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
  984. linelengths=1, linewidths=None, colors=None, alpha=None,
  985. linestyles='solid', **kwargs):
  986. """
  987. Plot identical parallel lines at the given positions.
  988. This type of plot is commonly used in neuroscience for representing
  989. neural events, where it is usually called a spike raster, dot raster,
  990. or raster plot.
  991. However, it is useful in any situation where you wish to show the
  992. timing or position of multiple sets of discrete events, such as the
  993. arrival times of people to a business on each day of the month or the
  994. date of hurricanes each year of the last century.
  995. Parameters
  996. ----------
  997. positions : array-like or list of array-like
  998. A 1D array-like defines the positions of one sequence of events.
  999. Multiple groups of events may be passed as a list of array-likes.
  1000. Each group can be styled independently by passing lists of values
  1001. to *lineoffsets*, *linelengths*, *linewidths*, *colors* and
  1002. *linestyles*.
  1003. Note that *positions* can be a 2D array, but in practice different
  1004. event groups usually have different counts so that one will use a
  1005. list of different-length arrays rather than a 2D array.
  1006. orientation : {'horizontal', 'vertical'}, default: 'horizontal'
  1007. The direction of the event sequence:
  1008. - 'horizontal': the events are arranged horizontally.
  1009. The indicator lines are vertical.
  1010. - 'vertical': the events are arranged vertically.
  1011. The indicator lines are horizontal.
  1012. lineoffsets : float or array-like, default: 1
  1013. The offset of the center of the lines from the origin, in the
  1014. direction orthogonal to *orientation*.
  1015. If *positions* is 2D, this can be a sequence with length matching
  1016. the length of *positions*.
  1017. linelengths : float or array-like, default: 1
  1018. The total height of the lines (i.e. the lines stretches from
  1019. ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
  1020. If *positions* is 2D, this can be a sequence with length matching
  1021. the length of *positions*.
  1022. linewidths : float or array-like, default: :rc:`lines.linewidth`
  1023. The line width(s) of the event lines, in points.
  1024. If *positions* is 2D, this can be a sequence with length matching
  1025. the length of *positions*.
  1026. colors : color or list of colors, default: :rc:`lines.color`
  1027. The color(s) of the event lines.
  1028. If *positions* is 2D, this can be a sequence with length matching
  1029. the length of *positions*.
  1030. alpha : float or array-like, default: 1
  1031. The alpha blending value(s), between 0 (transparent) and 1
  1032. (opaque).
  1033. If *positions* is 2D, this can be a sequence with length matching
  1034. the length of *positions*.
  1035. linestyles : str or tuple or list of such values, default: 'solid'
  1036. Default is 'solid'. Valid strings are ['solid', 'dashed',
  1037. 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples
  1038. should be of the form::
  1039. (offset, onoffseq),
  1040. where *onoffseq* is an even length tuple of on and off ink
  1041. in points.
  1042. If *positions* is 2D, this can be a sequence with length matching
  1043. the length of *positions*.
  1044. data : indexable object, optional
  1045. DATA_PARAMETER_PLACEHOLDER
  1046. **kwargs
  1047. Other keyword arguments are line collection properties. See
  1048. `.LineCollection` for a list of the valid properties.
  1049. Returns
  1050. -------
  1051. list of `.EventCollection`
  1052. The `.EventCollection` that were added.
  1053. Notes
  1054. -----
  1055. For *linelengths*, *linewidths*, *colors*, *alpha* and *linestyles*, if
  1056. only a single value is given, that value is applied to all lines. If an
  1057. array-like is given, it must have the same length as *positions*, and
  1058. each value will be applied to the corresponding row of the array.
  1059. Examples
  1060. --------
  1061. .. plot:: gallery/lines_bars_and_markers/eventplot_demo.py
  1062. """
  1063. lineoffsets, linelengths = self._process_unit_info(
  1064. [("y", lineoffsets), ("y", linelengths)], kwargs)
  1065. # fix positions, noting that it can be a list of lists:
  1066. if not np.iterable(positions):
  1067. positions = [positions]
  1068. elif any(np.iterable(position) for position in positions):
  1069. positions = [np.asanyarray(position) for position in positions]
  1070. else:
  1071. positions = [np.asanyarray(positions)]
  1072. poss = []
  1073. for position in positions:
  1074. poss += self._process_unit_info([("x", position)], kwargs)
  1075. positions = poss
  1076. # prevent 'singular' keys from **kwargs dict from overriding the effect
  1077. # of 'plural' keyword arguments (e.g. 'color' overriding 'colors')
  1078. colors = cbook._local_over_kwdict(colors, kwargs, 'color')
  1079. linewidths = cbook._local_over_kwdict(linewidths, kwargs, 'linewidth')
  1080. linestyles = cbook._local_over_kwdict(linestyles, kwargs, 'linestyle')
  1081. if not np.iterable(lineoffsets):
  1082. lineoffsets = [lineoffsets]
  1083. if not np.iterable(linelengths):
  1084. linelengths = [linelengths]
  1085. if not np.iterable(linewidths):
  1086. linewidths = [linewidths]
  1087. if not np.iterable(colors):
  1088. colors = [colors]
  1089. if not np.iterable(alpha):
  1090. alpha = [alpha]
  1091. if hasattr(linestyles, 'lower') or not np.iterable(linestyles):
  1092. linestyles = [linestyles]
  1093. lineoffsets = np.asarray(lineoffsets)
  1094. linelengths = np.asarray(linelengths)
  1095. linewidths = np.asarray(linewidths)
  1096. if len(lineoffsets) == 0:
  1097. raise ValueError('lineoffsets cannot be empty')
  1098. if len(linelengths) == 0:
  1099. raise ValueError('linelengths cannot be empty')
  1100. if len(linestyles) == 0:
  1101. raise ValueError('linestyles cannot be empty')
  1102. if len(linewidths) == 0:
  1103. raise ValueError('linewidths cannot be empty')
  1104. if len(alpha) == 0:
  1105. raise ValueError('alpha cannot be empty')
  1106. if len(colors) == 0:
  1107. colors = [None]
  1108. try:
  1109. # Early conversion of the colors into RGBA values to take care
  1110. # of cases like colors='0.5' or colors='C1'. (Issue #8193)
  1111. colors = mcolors.to_rgba_array(colors)
  1112. except ValueError:
  1113. # Will fail if any element of *colors* is None. But as long
  1114. # as len(colors) == 1 or len(positions), the rest of the
  1115. # code should process *colors* properly.
  1116. pass
  1117. if len(lineoffsets) == 1 and len(positions) != 1:
  1118. lineoffsets = np.tile(lineoffsets, len(positions))
  1119. lineoffsets[0] = 0
  1120. lineoffsets = np.cumsum(lineoffsets)
  1121. if len(linelengths) == 1:
  1122. linelengths = np.tile(linelengths, len(positions))
  1123. if len(linewidths) == 1:
  1124. linewidths = np.tile(linewidths, len(positions))
  1125. if len(colors) == 1:
  1126. colors = list(colors) * len(positions)
  1127. if len(alpha) == 1:
  1128. alpha = list(alpha) * len(positions)
  1129. if len(linestyles) == 1:
  1130. linestyles = [linestyles] * len(positions)
  1131. if len(lineoffsets) != len(positions):
  1132. raise ValueError('lineoffsets and positions are unequal sized '
  1133. 'sequences')
  1134. if len(linelengths) != len(positions):
  1135. raise ValueError('linelengths and positions are unequal sized '
  1136. 'sequences')
  1137. if len(linewidths) != len(positions):
  1138. raise ValueError('linewidths and positions are unequal sized '
  1139. 'sequences')
  1140. if len(colors) != len(positions):
  1141. raise ValueError('colors and positions are unequal sized '
  1142. 'sequences')
  1143. if len(alpha) != len(positions):
  1144. raise ValueError('alpha and positions are unequal sized '
  1145. 'sequences')
  1146. if len(linestyles) != len(positions):
  1147. raise ValueError('linestyles and positions are unequal sized '
  1148. 'sequences')
  1149. colls = []
  1150. for position, lineoffset, linelength, linewidth, color, alpha_, \
  1151. linestyle in \
  1152. zip(positions, lineoffsets, linelengths, linewidths,
  1153. colors, alpha, linestyles):
  1154. coll = mcoll.EventCollection(position,
  1155. orientation=orientation,
  1156. lineoffset=lineoffset,
  1157. linelength=linelength,
  1158. linewidth=linewidth,
  1159. color=color,
  1160. alpha=alpha_,
  1161. linestyle=linestyle)
  1162. self.add_collection(coll, autolim=False)
  1163. coll._internal_update(kwargs)
  1164. colls.append(coll)
  1165. if len(positions) > 0:
  1166. # try to get min/max
  1167. min_max = [(np.min(_p), np.max(_p)) for _p in positions
  1168. if len(_p) > 0]
  1169. # if we have any non-empty positions, try to autoscale
  1170. if len(min_max) > 0:
  1171. mins, maxes = zip(*min_max)
  1172. minpos = np.min(mins)
  1173. maxpos = np.max(maxes)
  1174. minline = (lineoffsets - linelengths).min()
  1175. maxline = (lineoffsets + linelengths).max()
  1176. if orientation == "vertical":
  1177. corners = (minline, minpos), (maxline, maxpos)
  1178. else: # "horizontal"
  1179. corners = (minpos, minline), (maxpos, maxline)
  1180. self.update_datalim(corners)
  1181. self._request_autoscale_view()
  1182. return colls
  1183. #### Basic plotting
  1184. # Uses a custom implementation of data-kwarg handling in
  1185. # _process_plot_var_args.
  1186. @_docstring.dedent_interpd
  1187. def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):
  1188. """
  1189. Plot y versus x as lines and/or markers.
  1190. Call signatures::
  1191. plot([x], y, [fmt], *, data=None, **kwargs)
  1192. plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
  1193. The coordinates of the points or line nodes are given by *x*, *y*.
  1194. The optional parameter *fmt* is a convenient way for defining basic
  1195. formatting like color, marker and linestyle. It's a shortcut string
  1196. notation described in the *Notes* section below.
  1197. >>> plot(x, y) # plot x and y using default line style and color
  1198. >>> plot(x, y, 'bo') # plot x and y using blue circle markers
  1199. >>> plot(y) # plot y using x as index array 0..N-1
  1200. >>> plot(y, 'r+') # ditto, but with red plusses
  1201. You can use `.Line2D` properties as keyword arguments for more
  1202. control on the appearance. Line properties and *fmt* can be mixed.
  1203. The following two calls yield identical results:
  1204. >>> plot(x, y, 'go--', linewidth=2, markersize=12)
  1205. >>> plot(x, y, color='green', marker='o', linestyle='dashed',
  1206. ... linewidth=2, markersize=12)
  1207. When conflicting with *fmt*, keyword arguments take precedence.
  1208. **Plotting labelled data**
  1209. There's a convenient way for plotting objects with labelled data (i.e.
  1210. data that can be accessed by index ``obj['y']``). Instead of giving
  1211. the data in *x* and *y*, you can provide the object in the *data*
  1212. parameter and just give the labels for *x* and *y*::
  1213. >>> plot('xlabel', 'ylabel', data=obj)
  1214. All indexable objects are supported. This could e.g. be a `dict`, a
  1215. `pandas.DataFrame` or a structured numpy array.
  1216. **Plotting multiple sets of data**
  1217. There are various ways to plot multiple sets of data.
  1218. - The most straight forward way is just to call `plot` multiple times.
  1219. Example:
  1220. >>> plot(x1, y1, 'bo')
  1221. >>> plot(x2, y2, 'go')
  1222. - If *x* and/or *y* are 2D arrays a separate data set will be drawn
  1223. for every column. If both *x* and *y* are 2D, they must have the
  1224. same shape. If only one of them is 2D with shape (N, m) the other
  1225. must have length N and will be used for every data set m.
  1226. Example:
  1227. >>> x = [1, 2, 3]
  1228. >>> y = np.array([[1, 2], [3, 4], [5, 6]])
  1229. >>> plot(x, y)
  1230. is equivalent to:
  1231. >>> for col in range(y.shape[1]):
  1232. ... plot(x, y[:, col])
  1233. - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]*
  1234. groups::
  1235. >>> plot(x1, y1, 'g^', x2, y2, 'g-')
  1236. In this case, any additional keyword argument applies to all
  1237. datasets. Also, this syntax cannot be combined with the *data*
  1238. parameter.
  1239. By default, each line is assigned a different style specified by a
  1240. 'style cycle'. The *fmt* and line property parameters are only
  1241. necessary if you want explicit deviations from these defaults.
  1242. Alternatively, you can also change the style cycle using
  1243. :rc:`axes.prop_cycle`.
  1244. Parameters
  1245. ----------
  1246. x, y : array-like or scalar
  1247. The horizontal / vertical coordinates of the data points.
  1248. *x* values are optional and default to ``range(len(y))``.
  1249. Commonly, these parameters are 1D arrays.
  1250. They can also be scalars, or two-dimensional (in that case, the
  1251. columns represent separate data sets).
  1252. These arguments cannot be passed as keywords.
  1253. fmt : str, optional
  1254. A format string, e.g. 'ro' for red circles. See the *Notes*
  1255. section for a full description of the format strings.
  1256. Format strings are just an abbreviation for quickly setting
  1257. basic line properties. All of these and more can also be
  1258. controlled by keyword arguments.
  1259. This argument cannot be passed as keyword.
  1260. data : indexable object, optional
  1261. An object with labelled data. If given, provide the label names to
  1262. plot in *x* and *y*.
  1263. .. note::
  1264. Technically there's a slight ambiguity in calls where the
  1265. second label is a valid *fmt*. ``plot('n', 'o', data=obj)``
  1266. could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases,
  1267. the former interpretation is chosen, but a warning is issued.
  1268. You may suppress the warning by adding an empty format string
  1269. ``plot('n', 'o', '', data=obj)``.
  1270. Returns
  1271. -------
  1272. list of `.Line2D`
  1273. A list of lines representing the plotted data.
  1274. Other Parameters
  1275. ----------------
  1276. scalex, scaley : bool, default: True
  1277. These parameters determine if the view limits are adapted to the
  1278. data limits. The values are passed on to
  1279. `~.axes.Axes.autoscale_view`.
  1280. **kwargs : `~matplotlib.lines.Line2D` properties, optional
  1281. *kwargs* are used to specify properties like a line label (for
  1282. auto legends), linewidth, antialiasing, marker face color.
  1283. Example::
  1284. >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
  1285. >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')
  1286. If you specify multiple lines with one plot call, the kwargs apply
  1287. to all those lines. In case the label object is iterable, each
  1288. element is used as labels for each set of data.
  1289. Here is a list of available `.Line2D` properties:
  1290. %(Line2D:kwdoc)s
  1291. See Also
  1292. --------
  1293. scatter : XY scatter plot with markers of varying size and/or color (
  1294. sometimes also called bubble chart).
  1295. Notes
  1296. -----
  1297. **Format Strings**
  1298. A format string consists of a part for color, marker and line::
  1299. fmt = '[marker][line][color]'
  1300. Each of them is optional. If not provided, the value from the style
  1301. cycle is used. Exception: If ``line`` is given, but no ``marker``,
  1302. the data will be a line without markers.
  1303. Other combinations such as ``[color][marker][line]`` are also
  1304. supported, but note that their parsing may be ambiguous.
  1305. **Markers**
  1306. ============= ===============================
  1307. character description
  1308. ============= ===============================
  1309. ``'.'`` point marker
  1310. ``','`` pixel marker
  1311. ``'o'`` circle marker
  1312. ``'v'`` triangle_down marker
  1313. ``'^'`` triangle_up marker
  1314. ``'<'`` triangle_left marker
  1315. ``'>'`` triangle_right marker
  1316. ``'1'`` tri_down marker
  1317. ``'2'`` tri_up marker
  1318. ``'3'`` tri_left marker
  1319. ``'4'`` tri_right marker
  1320. ``'8'`` octagon marker
  1321. ``'s'`` square marker
  1322. ``'p'`` pentagon marker
  1323. ``'P'`` plus (filled) marker
  1324. ``'*'`` star marker
  1325. ``'h'`` hexagon1 marker
  1326. ``'H'`` hexagon2 marker
  1327. ``'+'`` plus marker
  1328. ``'x'`` x marker
  1329. ``'X'`` x (filled) marker
  1330. ``'D'`` diamond marker
  1331. ``'d'`` thin_diamond marker
  1332. ``'|'`` vline marker
  1333. ``'_'`` hline marker
  1334. ============= ===============================
  1335. **Line Styles**
  1336. ============= ===============================
  1337. character description
  1338. ============= ===============================
  1339. ``'-'`` solid line style
  1340. ``'--'`` dashed line style
  1341. ``'-.'`` dash-dot line style
  1342. ``':'`` dotted line style
  1343. ============= ===============================
  1344. Example format strings::
  1345. 'b' # blue markers with default shape
  1346. 'or' # red circles
  1347. '-g' # green solid line
  1348. '--' # dashed line with default color
  1349. '^k:' # black triangle_up markers connected by a dotted line
  1350. **Colors**
  1351. The supported color abbreviations are the single letter codes
  1352. ============= ===============================
  1353. character color
  1354. ============= ===============================
  1355. ``'b'`` blue
  1356. ``'g'`` green
  1357. ``'r'`` red
  1358. ``'c'`` cyan
  1359. ``'m'`` magenta
  1360. ``'y'`` yellow
  1361. ``'k'`` black
  1362. ``'w'`` white
  1363. ============= ===============================
  1364. and the ``'CN'`` colors that index into the default property cycle.
  1365. If the color is the only part of the format string, you can
  1366. additionally use any `matplotlib.colors` spec, e.g. full names
  1367. (``'green'``) or hex strings (``'#008000'``).
  1368. """
  1369. kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
  1370. lines = [*self._get_lines(self, *args, data=data, **kwargs)]
  1371. for line in lines:
  1372. self.add_line(line)
  1373. if scalex:
  1374. self._request_autoscale_view("x")
  1375. if scaley:
  1376. self._request_autoscale_view("y")
  1377. return lines
  1378. @_preprocess_data(replace_names=["x", "y"], label_namer="y")
  1379. @_docstring.dedent_interpd
  1380. def plot_date(self, x, y, fmt='o', tz=None, xdate=True, ydate=False,
  1381. **kwargs):
  1382. """
  1383. [*Discouraged*] Plot coercing the axis to treat floats as dates.
  1384. .. admonition:: Discouraged
  1385. This method exists for historic reasons and will be deprecated in
  1386. the future.
  1387. - ``datetime``-like data should directly be plotted using
  1388. `~.Axes.plot`.
  1389. - If you need to plot plain numeric data as :ref:`date-format` or
  1390. need to set a timezone, call ``ax.xaxis.axis_date`` /
  1391. ``ax.yaxis.axis_date`` before `~.Axes.plot`. See
  1392. `.Axis.axis_date`.
  1393. Similar to `.plot`, this plots *y* vs. *x* as lines or markers.
  1394. However, the axis labels are formatted as dates depending on *xdate*
  1395. and *ydate*. Note that `.plot` will work with `datetime` and
  1396. `numpy.datetime64` objects without resorting to this method.
  1397. Parameters
  1398. ----------
  1399. x, y : array-like
  1400. The coordinates of the data points. If *xdate* or *ydate* is
  1401. *True*, the respective values *x* or *y* are interpreted as
  1402. :ref:`Matplotlib dates <date-format>`.
  1403. fmt : str, optional
  1404. The plot format string. For details, see the corresponding
  1405. parameter in `.plot`.
  1406. tz : timezone string or `datetime.tzinfo`, default: :rc:`timezone`
  1407. The time zone to use in labeling dates.
  1408. xdate : bool, default: True
  1409. If *True*, the *x*-axis will be interpreted as Matplotlib dates.
  1410. ydate : bool, default: False
  1411. If *True*, the *y*-axis will be interpreted as Matplotlib dates.
  1412. Returns
  1413. -------
  1414. list of `.Line2D`
  1415. Objects representing the plotted data.
  1416. Other Parameters
  1417. ----------------
  1418. data : indexable object, optional
  1419. DATA_PARAMETER_PLACEHOLDER
  1420. **kwargs
  1421. Keyword arguments control the `.Line2D` properties:
  1422. %(Line2D:kwdoc)s
  1423. See Also
  1424. --------
  1425. matplotlib.dates : Helper functions on dates.
  1426. matplotlib.dates.date2num : Convert dates to num.
  1427. matplotlib.dates.num2date : Convert num to dates.
  1428. matplotlib.dates.drange : Create an equally spaced sequence of dates.
  1429. Notes
  1430. -----
  1431. If you are using custom date tickers and formatters, it may be
  1432. necessary to set the formatters/locators after the call to
  1433. `.plot_date`. `.plot_date` will set the default tick locator to
  1434. `.AutoDateLocator` (if the tick locator is not already set to a
  1435. `.DateLocator` instance) and the default tick formatter to
  1436. `.AutoDateFormatter` (if the tick formatter is not already set to a
  1437. `.DateFormatter` instance).
  1438. """
  1439. if xdate:
  1440. self.xaxis_date(tz)
  1441. if ydate:
  1442. self.yaxis_date(tz)
  1443. return self.plot(x, y, fmt, **kwargs)
  1444. # @_preprocess_data() # let 'plot' do the unpacking..
  1445. @_docstring.dedent_interpd
  1446. def loglog(self, *args, **kwargs):
  1447. """
  1448. Make a plot with log scaling on both the x- and y-axis.
  1449. Call signatures::
  1450. loglog([x], y, [fmt], data=None, **kwargs)
  1451. loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
  1452. This is just a thin wrapper around `.plot` which additionally changes
  1453. both the x-axis and the y-axis to log scaling. All the concepts and
  1454. parameters of plot can be used here as well.
  1455. The additional parameters *base*, *subs* and *nonpositive* control the
  1456. x/y-axis properties. They are just forwarded to `.Axes.set_xscale` and
  1457. `.Axes.set_yscale`. To use different properties on the x-axis and the
  1458. y-axis, use e.g.
  1459. ``ax.set_xscale("log", base=10); ax.set_yscale("log", base=2)``.
  1460. Parameters
  1461. ----------
  1462. base : float, default: 10
  1463. Base of the logarithm.
  1464. subs : sequence, optional
  1465. The location of the minor ticks. If *None*, reasonable locations
  1466. are automatically chosen depending on the number of decades in the
  1467. plot. See `.Axes.set_xscale`/`.Axes.set_yscale` for details.
  1468. nonpositive : {'mask', 'clip'}, default: 'clip'
  1469. Non-positive values can be masked as invalid, or clipped to a very
  1470. small positive number.
  1471. **kwargs
  1472. All parameters supported by `.plot`.
  1473. Returns
  1474. -------
  1475. list of `.Line2D`
  1476. Objects representing the plotted data.
  1477. """
  1478. dx = {k: v for k, v in kwargs.items()
  1479. if k in ['base', 'subs', 'nonpositive',
  1480. 'basex', 'subsx', 'nonposx']}
  1481. self.set_xscale('log', **dx)
  1482. dy = {k: v for k, v in kwargs.items()
  1483. if k in ['base', 'subs', 'nonpositive',
  1484. 'basey', 'subsy', 'nonposy']}
  1485. self.set_yscale('log', **dy)
  1486. return self.plot(
  1487. *args, **{k: v for k, v in kwargs.items() if k not in {*dx, *dy}})
  1488. # @_preprocess_data() # let 'plot' do the unpacking..
  1489. @_docstring.dedent_interpd
  1490. def semilogx(self, *args, **kwargs):
  1491. """
  1492. Make a plot with log scaling on the x-axis.
  1493. Call signatures::
  1494. semilogx([x], y, [fmt], data=None, **kwargs)
  1495. semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
  1496. This is just a thin wrapper around `.plot` which additionally changes
  1497. the x-axis to log scaling. All the concepts and parameters of plot can
  1498. be used here as well.
  1499. The additional parameters *base*, *subs*, and *nonpositive* control the
  1500. x-axis properties. They are just forwarded to `.Axes.set_xscale`.
  1501. Parameters
  1502. ----------
  1503. base : float, default: 10
  1504. Base of the x logarithm.
  1505. subs : array-like, optional
  1506. The location of the minor xticks. If *None*, reasonable locations
  1507. are automatically chosen depending on the number of decades in the
  1508. plot. See `.Axes.set_xscale` for details.
  1509. nonpositive : {'mask', 'clip'}, default: 'clip'
  1510. Non-positive values in x can be masked as invalid, or clipped to a
  1511. very small positive number.
  1512. **kwargs
  1513. All parameters supported by `.plot`.
  1514. Returns
  1515. -------
  1516. list of `.Line2D`
  1517. Objects representing the plotted data.
  1518. """
  1519. d = {k: v for k, v in kwargs.items()
  1520. if k in ['base', 'subs', 'nonpositive',
  1521. 'basex', 'subsx', 'nonposx']}
  1522. self.set_xscale('log', **d)
  1523. return self.plot(
  1524. *args, **{k: v for k, v in kwargs.items() if k not in d})
  1525. # @_preprocess_data() # let 'plot' do the unpacking..
  1526. @_docstring.dedent_interpd
  1527. def semilogy(self, *args, **kwargs):
  1528. """
  1529. Make a plot with log scaling on the y-axis.
  1530. Call signatures::
  1531. semilogy([x], y, [fmt], data=None, **kwargs)
  1532. semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
  1533. This is just a thin wrapper around `.plot` which additionally changes
  1534. the y-axis to log scaling. All the concepts and parameters of plot can
  1535. be used here as well.
  1536. The additional parameters *base*, *subs*, and *nonpositive* control the
  1537. y-axis properties. They are just forwarded to `.Axes.set_yscale`.
  1538. Parameters
  1539. ----------
  1540. base : float, default: 10
  1541. Base of the y logarithm.
  1542. subs : array-like, optional
  1543. The location of the minor yticks. If *None*, reasonable locations
  1544. are automatically chosen depending on the number of decades in the
  1545. plot. See `.Axes.set_yscale` for details.
  1546. nonpositive : {'mask', 'clip'}, default: 'clip'
  1547. Non-positive values in y can be masked as invalid, or clipped to a
  1548. very small positive number.
  1549. **kwargs
  1550. All parameters supported by `.plot`.
  1551. Returns
  1552. -------
  1553. list of `.Line2D`
  1554. Objects representing the plotted data.
  1555. """
  1556. d = {k: v for k, v in kwargs.items()
  1557. if k in ['base', 'subs', 'nonpositive',
  1558. 'basey', 'subsy', 'nonposy']}
  1559. self.set_yscale('log', **d)
  1560. return self.plot(
  1561. *args, **{k: v for k, v in kwargs.items() if k not in d})
  1562. @_preprocess_data(replace_names=["x"], label_namer="x")
  1563. def acorr(self, x, **kwargs):
  1564. """
  1565. Plot the autocorrelation of *x*.
  1566. Parameters
  1567. ----------
  1568. x : array-like
  1569. detrend : callable, default: `.mlab.detrend_none` (no detrending)
  1570. A detrending function applied to *x*. It must have the
  1571. signature ::
  1572. detrend(x: np.ndarray) -> np.ndarray
  1573. normed : bool, default: True
  1574. If ``True``, input vectors are normalised to unit length.
  1575. usevlines : bool, default: True
  1576. Determines the plot style.
  1577. If ``True``, vertical lines are plotted from 0 to the acorr value
  1578. using `.Axes.vlines`. Additionally, a horizontal line is plotted
  1579. at y=0 using `.Axes.axhline`.
  1580. If ``False``, markers are plotted at the acorr values using
  1581. `.Axes.plot`.
  1582. maxlags : int, default: 10
  1583. Number of lags to show. If ``None``, will return all
  1584. ``2 * len(x) - 1`` lags.
  1585. Returns
  1586. -------
  1587. lags : array (length ``2*maxlags+1``)
  1588. The lag vector.
  1589. c : array (length ``2*maxlags+1``)
  1590. The auto correlation vector.
  1591. line : `.LineCollection` or `.Line2D`
  1592. `.Artist` added to the Axes of the correlation:
  1593. - `.LineCollection` if *usevlines* is True.
  1594. - `.Line2D` if *usevlines* is False.
  1595. b : `~matplotlib.lines.Line2D` or None
  1596. Horizontal line at 0 if *usevlines* is True
  1597. None *usevlines* is False.
  1598. Other Parameters
  1599. ----------------
  1600. linestyle : `~matplotlib.lines.Line2D` property, optional
  1601. The linestyle for plotting the data points.
  1602. Only used if *usevlines* is ``False``.
  1603. marker : str, default: 'o'
  1604. The marker for plotting the data points.
  1605. Only used if *usevlines* is ``False``.
  1606. data : indexable object, optional
  1607. DATA_PARAMETER_PLACEHOLDER
  1608. **kwargs
  1609. Additional parameters are passed to `.Axes.vlines` and
  1610. `.Axes.axhline` if *usevlines* is ``True``; otherwise they are
  1611. passed to `.Axes.plot`.
  1612. Notes
  1613. -----
  1614. The cross correlation is performed with `numpy.correlate` with
  1615. ``mode = "full"``.
  1616. """
  1617. return self.xcorr(x, x, **kwargs)
  1618. @_preprocess_data(replace_names=["x", "y"], label_namer="y")
  1619. def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
  1620. usevlines=True, maxlags=10, **kwargs):
  1621. r"""
  1622. Plot the cross correlation between *x* and *y*.
  1623. The correlation with lag k is defined as
  1624. :math:`\sum_n x[n+k] \cdot y^*[n]`, where :math:`y^*` is the complex
  1625. conjugate of :math:`y`.
  1626. Parameters
  1627. ----------
  1628. x, y : array-like of length n
  1629. detrend : callable, default: `.mlab.detrend_none` (no detrending)
  1630. A detrending function applied to *x* and *y*. It must have the
  1631. signature ::
  1632. detrend(x: np.ndarray) -> np.ndarray
  1633. normed : bool, default: True
  1634. If ``True``, input vectors are normalised to unit length.
  1635. usevlines : bool, default: True
  1636. Determines the plot style.
  1637. If ``True``, vertical lines are plotted from 0 to the xcorr value
  1638. using `.Axes.vlines`. Additionally, a horizontal line is plotted
  1639. at y=0 using `.Axes.axhline`.
  1640. If ``False``, markers are plotted at the xcorr values using
  1641. `.Axes.plot`.
  1642. maxlags : int, default: 10
  1643. Number of lags to show. If None, will return all ``2 * len(x) - 1``
  1644. lags.
  1645. Returns
  1646. -------
  1647. lags : array (length ``2*maxlags+1``)
  1648. The lag vector.
  1649. c : array (length ``2*maxlags+1``)
  1650. The auto correlation vector.
  1651. line : `.LineCollection` or `.Line2D`
  1652. `.Artist` added to the Axes of the correlation:
  1653. - `.LineCollection` if *usevlines* is True.
  1654. - `.Line2D` if *usevlines* is False.
  1655. b : `~matplotlib.lines.Line2D` or None
  1656. Horizontal line at 0 if *usevlines* is True
  1657. None *usevlines* is False.
  1658. Other Parameters
  1659. ----------------
  1660. linestyle : `~matplotlib.lines.Line2D` property, optional
  1661. The linestyle for plotting the data points.
  1662. Only used if *usevlines* is ``False``.
  1663. marker : str, default: 'o'
  1664. The marker for plotting the data points.
  1665. Only used if *usevlines* is ``False``.
  1666. data : indexable object, optional
  1667. DATA_PARAMETER_PLACEHOLDER
  1668. **kwargs
  1669. Additional parameters are passed to `.Axes.vlines` and
  1670. `.Axes.axhline` if *usevlines* is ``True``; otherwise they are
  1671. passed to `.Axes.plot`.
  1672. Notes
  1673. -----
  1674. The cross correlation is performed with `numpy.correlate` with
  1675. ``mode = "full"``.
  1676. """
  1677. Nx = len(x)
  1678. if Nx != len(y):
  1679. raise ValueError('x and y must be equal length')
  1680. x = detrend(np.asarray(x))
  1681. y = detrend(np.asarray(y))
  1682. correls = np.correlate(x, y, mode="full")
  1683. if normed:
  1684. correls = correls / np.sqrt(np.dot(x, x) * np.dot(y, y))
  1685. if maxlags is None:
  1686. maxlags = Nx - 1
  1687. if maxlags >= Nx or maxlags < 1:
  1688. raise ValueError('maxlags must be None or strictly '
  1689. 'positive < %d' % Nx)
  1690. lags = np.arange(-maxlags, maxlags + 1)
  1691. correls = correls[Nx - 1 - maxlags:Nx + maxlags]
  1692. if usevlines:
  1693. a = self.vlines(lags, [0], correls, **kwargs)
  1694. # Make label empty so only vertical lines get a legend entry
  1695. kwargs.pop('label', '')
  1696. b = self.axhline(**kwargs)
  1697. else:
  1698. kwargs.setdefault('marker', 'o')
  1699. kwargs.setdefault('linestyle', 'None')
  1700. a, = self.plot(lags, correls, **kwargs)
  1701. b = None
  1702. return lags, correls, a, b
  1703. #### Specialized plotting
  1704. # @_preprocess_data() # let 'plot' do the unpacking..
  1705. def step(self, x, y, *args, where='pre', data=None, **kwargs):
  1706. """
  1707. Make a step plot.
  1708. Call signatures::
  1709. step(x, y, [fmt], *, data=None, where='pre', **kwargs)
  1710. step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)
  1711. This is just a thin wrapper around `.plot` which changes some
  1712. formatting options. Most of the concepts and parameters of plot can be
  1713. used here as well.
  1714. .. note::
  1715. This method uses a standard plot with a step drawstyle: The *x*
  1716. values are the reference positions and steps extend left/right/both
  1717. directions depending on *where*.
  1718. For the common case where you know the values and edges of the
  1719. steps, use `~.Axes.stairs` instead.
  1720. Parameters
  1721. ----------
  1722. x : array-like
  1723. 1D sequence of x positions. It is assumed, but not checked, that
  1724. it is uniformly increasing.
  1725. y : array-like
  1726. 1D sequence of y levels.
  1727. fmt : str, optional
  1728. A format string, e.g. 'g' for a green line. See `.plot` for a more
  1729. detailed description.
  1730. Note: While full format strings are accepted, it is recommended to
  1731. only specify the color. Line styles are currently ignored (use
  1732. the keyword argument *linestyle* instead). Markers are accepted
  1733. and plotted on the given positions, however, this is a rarely
  1734. needed feature for step plots.
  1735. where : {'pre', 'post', 'mid'}, default: 'pre'
  1736. Define where the steps should be placed:
  1737. - 'pre': The y value is continued constantly to the left from
  1738. every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the
  1739. value ``y[i]``.
  1740. - 'post': The y value is continued constantly to the right from
  1741. every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the
  1742. value ``y[i]``.
  1743. - 'mid': Steps occur half-way between the *x* positions.
  1744. data : indexable object, optional
  1745. An object with labelled data. If given, provide the label names to
  1746. plot in *x* and *y*.
  1747. **kwargs
  1748. Additional parameters are the same as those for `.plot`.
  1749. Returns
  1750. -------
  1751. list of `.Line2D`
  1752. Objects representing the plotted data.
  1753. """
  1754. _api.check_in_list(('pre', 'post', 'mid'), where=where)
  1755. kwargs['drawstyle'] = 'steps-' + where
  1756. return self.plot(x, y, *args, data=data, **kwargs)
  1757. @staticmethod
  1758. def _convert_dx(dx, x0, xconv, convert):
  1759. """
  1760. Small helper to do logic of width conversion flexibly.
  1761. *dx* and *x0* have units, but *xconv* has already been converted
  1762. to unitless (and is an ndarray). This allows the *dx* to have units
  1763. that are different from *x0*, but are still accepted by the
  1764. ``__add__`` operator of *x0*.
  1765. """
  1766. # x should be an array...
  1767. assert type(xconv) is np.ndarray
  1768. if xconv.size == 0:
  1769. # xconv has already been converted, but maybe empty...
  1770. return convert(dx)
  1771. try:
  1772. # attempt to add the width to x0; this works for
  1773. # datetime+timedelta, for instance
  1774. # only use the first element of x and x0. This saves
  1775. # having to be sure addition works across the whole
  1776. # vector. This is particularly an issue if
  1777. # x0 and dx are lists so x0 + dx just concatenates the lists.
  1778. # We can't just cast x0 and dx to numpy arrays because that
  1779. # removes the units from unit packages like `pint` that
  1780. # wrap numpy arrays.
  1781. try:
  1782. x0 = cbook._safe_first_finite(x0)
  1783. except (TypeError, IndexError, KeyError):
  1784. pass
  1785. try:
  1786. x = cbook._safe_first_finite(xconv)
  1787. except (TypeError, IndexError, KeyError):
  1788. x = xconv
  1789. delist = False
  1790. if not np.iterable(dx):
  1791. dx = [dx]
  1792. delist = True
  1793. dx = [convert(x0 + ddx) - x for ddx in dx]
  1794. if delist:
  1795. dx = dx[0]
  1796. except (ValueError, TypeError, AttributeError):
  1797. # if the above fails (for any reason) just fallback to what
  1798. # we do by default and convert dx by itself.
  1799. dx = convert(dx)
  1800. return dx
  1801. @_preprocess_data()
  1802. @_docstring.dedent_interpd
  1803. def bar(self, x, height, width=0.8, bottom=None, *, align="center",
  1804. **kwargs):
  1805. r"""
  1806. Make a bar plot.
  1807. The bars are positioned at *x* with the given *align*\ment. Their
  1808. dimensions are given by *height* and *width*. The vertical baseline
  1809. is *bottom* (default 0).
  1810. Many parameters can take either a single value applying to all bars
  1811. or a sequence of values, one for each bar.
  1812. Parameters
  1813. ----------
  1814. x : float or array-like
  1815. The x coordinates of the bars. See also *align* for the
  1816. alignment of the bars to the coordinates.
  1817. height : float or array-like
  1818. The height(s) of the bars.
  1819. Note that if *bottom* has units (e.g. datetime), *height* should be in
  1820. units that are a difference from the value of *bottom* (e.g. timedelta).
  1821. width : float or array-like, default: 0.8
  1822. The width(s) of the bars.
  1823. Note that if *x* has units (e.g. datetime), then *width* should be in
  1824. units that are a difference (e.g. timedelta) around the *x* values.
  1825. bottom : float or array-like, default: 0
  1826. The y coordinate(s) of the bottom side(s) of the bars.
  1827. Note that if *bottom* has units, then the y-axis will get a Locator and
  1828. Formatter appropriate for the units (e.g. dates, or categorical).
  1829. align : {'center', 'edge'}, default: 'center'
  1830. Alignment of the bars to the *x* coordinates:
  1831. - 'center': Center the base on the *x* positions.
  1832. - 'edge': Align the left edges of the bars with the *x* positions.
  1833. To align the bars on the right edge pass a negative *width* and
  1834. ``align='edge'``.
  1835. Returns
  1836. -------
  1837. `.BarContainer`
  1838. Container with all the bars and optionally errorbars.
  1839. Other Parameters
  1840. ----------------
  1841. color : color or list of color, optional
  1842. The colors of the bar faces.
  1843. edgecolor : color or list of color, optional
  1844. The colors of the bar edges.
  1845. linewidth : float or array-like, optional
  1846. Width of the bar edge(s). If 0, don't draw edges.
  1847. tick_label : str or list of str, optional
  1848. The tick labels of the bars.
  1849. Default: None (Use default numeric labels.)
  1850. label : str or list of str, optional
  1851. A single label is attached to the resulting `.BarContainer` as a
  1852. label for the whole dataset.
  1853. If a list is provided, it must be the same length as *x* and
  1854. labels the individual bars. Repeated labels are not de-duplicated
  1855. and will cause repeated label entries, so this is best used when
  1856. bars also differ in style (e.g., by passing a list to *color*.)
  1857. xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional
  1858. If not *None*, add horizontal / vertical errorbars to the bar tips.
  1859. The values are +/- sizes relative to the data:
  1860. - scalar: symmetric +/- values for all bars
  1861. - shape(N,): symmetric +/- values for each bar
  1862. - shape(2, N): Separate - and + values for each bar. First row
  1863. contains the lower errors, the second row contains the upper
  1864. errors.
  1865. - *None*: No errorbar. (Default)
  1866. See :doc:`/gallery/statistics/errorbar_features` for an example on
  1867. the usage of *xerr* and *yerr*.
  1868. ecolor : color or list of color, default: 'black'
  1869. The line color of the errorbars.
  1870. capsize : float, default: :rc:`errorbar.capsize`
  1871. The length of the error bar caps in points.
  1872. error_kw : dict, optional
  1873. Dictionary of keyword arguments to be passed to the
  1874. `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined
  1875. here take precedence over the independent keyword arguments.
  1876. log : bool, default: False
  1877. If *True*, set the y-axis to be log scale.
  1878. data : indexable object, optional
  1879. DATA_PARAMETER_PLACEHOLDER
  1880. **kwargs : `.Rectangle` properties
  1881. %(Rectangle:kwdoc)s
  1882. See Also
  1883. --------
  1884. barh : Plot a horizontal bar plot.
  1885. Notes
  1886. -----
  1887. Stacked bars can be achieved by passing individual *bottom* values per
  1888. bar. See :doc:`/gallery/lines_bars_and_markers/bar_stacked`.
  1889. """
  1890. kwargs = cbook.normalize_kwargs(kwargs, mpatches.Patch)
  1891. color = kwargs.pop('color', None)
  1892. if color is None:
  1893. color = self._get_patches_for_fill.get_next_color()
  1894. edgecolor = kwargs.pop('edgecolor', None)
  1895. linewidth = kwargs.pop('linewidth', None)
  1896. hatch = kwargs.pop('hatch', None)
  1897. # Because xerr and yerr will be passed to errorbar, most dimension
  1898. # checking and processing will be left to the errorbar method.
  1899. xerr = kwargs.pop('xerr', None)
  1900. yerr = kwargs.pop('yerr', None)
  1901. error_kw = kwargs.pop('error_kw', {})
  1902. ezorder = error_kw.pop('zorder', None)
  1903. if ezorder is None:
  1904. ezorder = kwargs.get('zorder', None)
  1905. if ezorder is not None:
  1906. # If using the bar zorder, increment slightly to make sure
  1907. # errorbars are drawn on top of bars
  1908. ezorder += 0.01
  1909. error_kw.setdefault('zorder', ezorder)
  1910. ecolor = kwargs.pop('ecolor', 'k')
  1911. capsize = kwargs.pop('capsize', mpl.rcParams["errorbar.capsize"])
  1912. error_kw.setdefault('ecolor', ecolor)
  1913. error_kw.setdefault('capsize', capsize)
  1914. # The keyword argument *orientation* is used by barh() to defer all
  1915. # logic and drawing to bar(). It is considered internal and is
  1916. # intentionally not mentioned in the docstring.
  1917. orientation = kwargs.pop('orientation', 'vertical')
  1918. _api.check_in_list(['vertical', 'horizontal'], orientation=orientation)
  1919. log = kwargs.pop('log', False)
  1920. label = kwargs.pop('label', '')
  1921. tick_labels = kwargs.pop('tick_label', None)
  1922. y = bottom # Matches barh call signature.
  1923. if orientation == 'vertical':
  1924. if y is None:
  1925. y = 0
  1926. else: # horizontal
  1927. if x is None:
  1928. x = 0
  1929. if orientation == 'vertical':
  1930. # It is possible for y (bottom) to contain unit information.
  1931. # However, it is also possible for y=0 for the default and height
  1932. # to contain unit information. This will prioritize the units of y.
  1933. self._process_unit_info(
  1934. [("x", x), ("y", y), ("y", height)], kwargs, convert=False)
  1935. if log:
  1936. self.set_yscale('log', nonpositive='clip')
  1937. else: # horizontal
  1938. # It is possible for x (left) to contain unit information.
  1939. # However, it is also possible for x=0 for the default and width
  1940. # to contain unit information. This will prioritize the units of x.
  1941. self._process_unit_info(
  1942. [("x", x), ("x", width), ("y", y)], kwargs, convert=False)
  1943. if log:
  1944. self.set_xscale('log', nonpositive='clip')
  1945. # lets do some conversions now since some types cannot be
  1946. # subtracted uniformly
  1947. if self.xaxis is not None:
  1948. x0 = x
  1949. x = np.asarray(self.convert_xunits(x))
  1950. width = self._convert_dx(width, x0, x, self.convert_xunits)
  1951. if xerr is not None:
  1952. xerr = self._convert_dx(xerr, x0, x, self.convert_xunits)
  1953. if self.yaxis is not None:
  1954. y0 = y
  1955. y = np.asarray(self.convert_yunits(y))
  1956. height = self._convert_dx(height, y0, y, self.convert_yunits)
  1957. if yerr is not None:
  1958. yerr = self._convert_dx(yerr, y0, y, self.convert_yunits)
  1959. x, height, width, y, linewidth, hatch = np.broadcast_arrays(
  1960. # Make args iterable too.
  1961. np.atleast_1d(x), height, width, y, linewidth, hatch)
  1962. # Now that units have been converted, set the tick locations.
  1963. if orientation == 'vertical':
  1964. tick_label_axis = self.xaxis
  1965. tick_label_position = x
  1966. else: # horizontal
  1967. tick_label_axis = self.yaxis
  1968. tick_label_position = y
  1969. if not isinstance(label, str) and np.iterable(label):
  1970. bar_container_label = '_nolegend_'
  1971. patch_labels = label
  1972. else:
  1973. bar_container_label = label
  1974. patch_labels = ['_nolegend_'] * len(x)
  1975. if len(patch_labels) != len(x):
  1976. raise ValueError(f'number of labels ({len(patch_labels)}) '
  1977. f'does not match number of bars ({len(x)}).')
  1978. linewidth = itertools.cycle(np.atleast_1d(linewidth))
  1979. hatch = itertools.cycle(np.atleast_1d(hatch))
  1980. color = itertools.chain(itertools.cycle(mcolors.to_rgba_array(color)),
  1981. # Fallback if color == "none".
  1982. itertools.repeat('none'))
  1983. if edgecolor is None:
  1984. edgecolor = itertools.repeat(None)
  1985. else:
  1986. edgecolor = itertools.chain(
  1987. itertools.cycle(mcolors.to_rgba_array(edgecolor)),
  1988. # Fallback if edgecolor == "none".
  1989. itertools.repeat('none'))
  1990. # We will now resolve the alignment and really have
  1991. # left, bottom, width, height vectors
  1992. _api.check_in_list(['center', 'edge'], align=align)
  1993. if align == 'center':
  1994. if orientation == 'vertical':
  1995. try:
  1996. left = x - width / 2
  1997. except TypeError as e:
  1998. raise TypeError(f'the dtypes of parameters x ({x.dtype}) '
  1999. f'and width ({width.dtype}) '
  2000. f'are incompatible') from e
  2001. bottom = y
  2002. else: # horizontal
  2003. try:
  2004. bottom = y - height / 2
  2005. except TypeError as e:
  2006. raise TypeError(f'the dtypes of parameters y ({y.dtype}) '
  2007. f'and height ({height.dtype}) '
  2008. f'are incompatible') from e
  2009. left = x
  2010. else: # edge
  2011. left = x
  2012. bottom = y
  2013. patches = []
  2014. args = zip(left, bottom, width, height, color, edgecolor, linewidth,
  2015. hatch, patch_labels)
  2016. for l, b, w, h, c, e, lw, htch, lbl in args:
  2017. r = mpatches.Rectangle(
  2018. xy=(l, b), width=w, height=h,
  2019. facecolor=c,
  2020. edgecolor=e,
  2021. linewidth=lw,
  2022. label=lbl,
  2023. hatch=htch,
  2024. )
  2025. r._internal_update(kwargs)
  2026. r.get_path()._interpolation_steps = 100
  2027. if orientation == 'vertical':
  2028. r.sticky_edges.y.append(b)
  2029. else: # horizontal
  2030. r.sticky_edges.x.append(l)
  2031. self.add_patch(r)
  2032. patches.append(r)
  2033. if xerr is not None or yerr is not None:
  2034. if orientation == 'vertical':
  2035. # using list comps rather than arrays to preserve unit info
  2036. ex = [l + 0.5 * w for l, w in zip(left, width)]
  2037. ey = [b + h for b, h in zip(bottom, height)]
  2038. else: # horizontal
  2039. # using list comps rather than arrays to preserve unit info
  2040. ex = [l + w for l, w in zip(left, width)]
  2041. ey = [b + 0.5 * h for b, h in zip(bottom, height)]
  2042. error_kw.setdefault("label", '_nolegend_')
  2043. errorbar = self.errorbar(ex, ey,
  2044. yerr=yerr, xerr=xerr,
  2045. fmt='none', **error_kw)
  2046. else:
  2047. errorbar = None
  2048. self._request_autoscale_view()
  2049. if orientation == 'vertical':
  2050. datavalues = height
  2051. else: # horizontal
  2052. datavalues = width
  2053. bar_container = BarContainer(patches, errorbar, datavalues=datavalues,
  2054. orientation=orientation,
  2055. label=bar_container_label)
  2056. self.add_container(bar_container)
  2057. if tick_labels is not None:
  2058. tick_labels = np.broadcast_to(tick_labels, len(patches))
  2059. tick_label_axis.set_ticks(tick_label_position)
  2060. tick_label_axis.set_ticklabels(tick_labels)
  2061. return bar_container
  2062. # @_preprocess_data() # let 'bar' do the unpacking..
  2063. @_docstring.dedent_interpd
  2064. def barh(self, y, width, height=0.8, left=None, *, align="center",
  2065. data=None, **kwargs):
  2066. r"""
  2067. Make a horizontal bar plot.
  2068. The bars are positioned at *y* with the given *align*\ment. Their
  2069. dimensions are given by *width* and *height*. The horizontal baseline
  2070. is *left* (default 0).
  2071. Many parameters can take either a single value applying to all bars
  2072. or a sequence of values, one for each bar.
  2073. Parameters
  2074. ----------
  2075. y : float or array-like
  2076. The y coordinates of the bars. See also *align* for the
  2077. alignment of the bars to the coordinates.
  2078. width : float or array-like
  2079. The width(s) of the bars.
  2080. Note that if *left* has units (e.g. datetime), *width* should be in
  2081. units that are a difference from the value of *left* (e.g. timedelta).
  2082. height : float or array-like, default: 0.8
  2083. The heights of the bars.
  2084. Note that if *y* has units (e.g. datetime), then *height* should be in
  2085. units that are a difference (e.g. timedelta) around the *y* values.
  2086. left : float or array-like, default: 0
  2087. The x coordinates of the left side(s) of the bars.
  2088. Note that if *left* has units, then the x-axis will get a Locator and
  2089. Formatter appropriate for the units (e.g. dates, or categorical).
  2090. align : {'center', 'edge'}, default: 'center'
  2091. Alignment of the base to the *y* coordinates*:
  2092. - 'center': Center the bars on the *y* positions.
  2093. - 'edge': Align the bottom edges of the bars with the *y*
  2094. positions.
  2095. To align the bars on the top edge pass a negative *height* and
  2096. ``align='edge'``.
  2097. Returns
  2098. -------
  2099. `.BarContainer`
  2100. Container with all the bars and optionally errorbars.
  2101. Other Parameters
  2102. ----------------
  2103. color : color or list of color, optional
  2104. The colors of the bar faces.
  2105. edgecolor : color or list of color, optional
  2106. The colors of the bar edges.
  2107. linewidth : float or array-like, optional
  2108. Width of the bar edge(s). If 0, don't draw edges.
  2109. tick_label : str or list of str, optional
  2110. The tick labels of the bars.
  2111. Default: None (Use default numeric labels.)
  2112. label : str or list of str, optional
  2113. A single label is attached to the resulting `.BarContainer` as a
  2114. label for the whole dataset.
  2115. If a list is provided, it must be the same length as *y* and
  2116. labels the individual bars. Repeated labels are not de-duplicated
  2117. and will cause repeated label entries, so this is best used when
  2118. bars also differ in style (e.g., by passing a list to *color*.)
  2119. xerr, yerr : float or array-like of shape(N,) or shape(2, N), optional
  2120. If not *None*, add horizontal / vertical errorbars to the bar tips.
  2121. The values are +/- sizes relative to the data:
  2122. - scalar: symmetric +/- values for all bars
  2123. - shape(N,): symmetric +/- values for each bar
  2124. - shape(2, N): Separate - and + values for each bar. First row
  2125. contains the lower errors, the second row contains the upper
  2126. errors.
  2127. - *None*: No errorbar. (default)
  2128. See :doc:`/gallery/statistics/errorbar_features` for an example on
  2129. the usage of *xerr* and *yerr*.
  2130. ecolor : color or list of color, default: 'black'
  2131. The line color of the errorbars.
  2132. capsize : float, default: :rc:`errorbar.capsize`
  2133. The length of the error bar caps in points.
  2134. error_kw : dict, optional
  2135. Dictionary of keyword arguments to be passed to the
  2136. `~.Axes.errorbar` method. Values of *ecolor* or *capsize* defined
  2137. here take precedence over the independent keyword arguments.
  2138. log : bool, default: False
  2139. If ``True``, set the x-axis to be log scale.
  2140. data : indexable object, optional
  2141. If given, all parameters also accept a string ``s``, which is
  2142. interpreted as ``data[s]`` (unless this raises an exception).
  2143. **kwargs : `.Rectangle` properties
  2144. %(Rectangle:kwdoc)s
  2145. See Also
  2146. --------
  2147. bar : Plot a vertical bar plot.
  2148. Notes
  2149. -----
  2150. Stacked bars can be achieved by passing individual *left* values per
  2151. bar. See
  2152. :doc:`/gallery/lines_bars_and_markers/horizontal_barchart_distribution`.
  2153. """
  2154. kwargs.setdefault('orientation', 'horizontal')
  2155. patches = self.bar(x=left, height=height, width=width, bottom=y,
  2156. align=align, data=data, **kwargs)
  2157. return patches
  2158. def bar_label(self, container, labels=None, *, fmt="%g", label_type="edge",
  2159. padding=0, **kwargs):
  2160. """
  2161. Label a bar plot.
  2162. Adds labels to bars in the given `.BarContainer`.
  2163. You may need to adjust the axis limits to fit the labels.
  2164. Parameters
  2165. ----------
  2166. container : `.BarContainer`
  2167. Container with all the bars and optionally errorbars, likely
  2168. returned from `.bar` or `.barh`.
  2169. labels : array-like, optional
  2170. A list of label texts, that should be displayed. If not given, the
  2171. label texts will be the data values formatted with *fmt*.
  2172. fmt : str or callable, default: '%g'
  2173. An unnamed %-style or {}-style format string for the label or a
  2174. function to call with the value as the first argument.
  2175. When *fmt* is a string and can be interpreted in both formats,
  2176. %-style takes precedence over {}-style.
  2177. .. versionadded:: 3.7
  2178. Support for {}-style format string and callables.
  2179. label_type : {'edge', 'center'}, default: 'edge'
  2180. The label type. Possible values:
  2181. - 'edge': label placed at the end-point of the bar segment, and the
  2182. value displayed will be the position of that end-point.
  2183. - 'center': label placed in the center of the bar segment, and the
  2184. value displayed will be the length of that segment.
  2185. (useful for stacked bars, i.e.,
  2186. :doc:`/gallery/lines_bars_and_markers/bar_label_demo`)
  2187. padding : float, default: 0
  2188. Distance of label from the end of the bar, in points.
  2189. **kwargs
  2190. Any remaining keyword arguments are passed through to
  2191. `.Axes.annotate`. The alignment parameters (
  2192. *horizontalalignment* / *ha*, *verticalalignment* / *va*) are
  2193. not supported because the labels are automatically aligned to
  2194. the bars.
  2195. Returns
  2196. -------
  2197. list of `.Annotation`
  2198. A list of `.Annotation` instances for the labels.
  2199. """
  2200. for key in ['horizontalalignment', 'ha', 'verticalalignment', 'va']:
  2201. if key in kwargs:
  2202. raise ValueError(
  2203. f"Passing {key!r} to bar_label() is not supported.")
  2204. a, b = self.yaxis.get_view_interval()
  2205. y_inverted = a > b
  2206. c, d = self.xaxis.get_view_interval()
  2207. x_inverted = c > d
  2208. # want to know whether to put label on positive or negative direction
  2209. # cannot use np.sign here because it will return 0 if x == 0
  2210. def sign(x):
  2211. return 1 if x >= 0 else -1
  2212. _api.check_in_list(['edge', 'center'], label_type=label_type)
  2213. bars = container.patches
  2214. errorbar = container.errorbar
  2215. datavalues = container.datavalues
  2216. orientation = container.orientation
  2217. if errorbar:
  2218. # check "ErrorbarContainer" for the definition of these elements
  2219. lines = errorbar.lines # attribute of "ErrorbarContainer" (tuple)
  2220. barlinecols = lines[2] # 0: data_line, 1: caplines, 2: barlinecols
  2221. barlinecol = barlinecols[0] # the "LineCollection" of error bars
  2222. errs = barlinecol.get_segments()
  2223. else:
  2224. errs = []
  2225. if labels is None:
  2226. labels = []
  2227. annotations = []
  2228. for bar, err, dat, lbl in itertools.zip_longest(
  2229. bars, errs, datavalues, labels
  2230. ):
  2231. (x0, y0), (x1, y1) = bar.get_bbox().get_points()
  2232. xc, yc = (x0 + x1) / 2, (y0 + y1) / 2
  2233. if orientation == "vertical":
  2234. extrema = max(y0, y1) if dat >= 0 else min(y0, y1)
  2235. length = abs(y0 - y1)
  2236. else: # horizontal
  2237. extrema = max(x0, x1) if dat >= 0 else min(x0, x1)
  2238. length = abs(x0 - x1)
  2239. if err is None or np.size(err) == 0:
  2240. endpt = extrema
  2241. elif orientation == "vertical":
  2242. endpt = err[:, 1].max() if dat >= 0 else err[:, 1].min()
  2243. else: # horizontal
  2244. endpt = err[:, 0].max() if dat >= 0 else err[:, 0].min()
  2245. if label_type == "center":
  2246. value = sign(dat) * length
  2247. else: # edge
  2248. value = extrema
  2249. if label_type == "center":
  2250. xy = (0.5, 0.5)
  2251. kwargs["xycoords"] = (
  2252. lambda r, b=bar:
  2253. mtransforms.Bbox.intersection(
  2254. b.get_window_extent(r), b.get_clip_box()
  2255. ) or mtransforms.Bbox.null()
  2256. )
  2257. else: # edge
  2258. if orientation == "vertical":
  2259. xy = xc, endpt
  2260. else: # horizontal
  2261. xy = endpt, yc
  2262. if orientation == "vertical":
  2263. y_direction = -1 if y_inverted else 1
  2264. xytext = 0, y_direction * sign(dat) * padding
  2265. else: # horizontal
  2266. x_direction = -1 if x_inverted else 1
  2267. xytext = x_direction * sign(dat) * padding, 0
  2268. if label_type == "center":
  2269. ha, va = "center", "center"
  2270. else: # edge
  2271. if orientation == "vertical":
  2272. ha = 'center'
  2273. if y_inverted:
  2274. va = 'top' if dat > 0 else 'bottom' # also handles NaN
  2275. else:
  2276. va = 'top' if dat < 0 else 'bottom' # also handles NaN
  2277. else: # horizontal
  2278. if x_inverted:
  2279. ha = 'right' if dat > 0 else 'left' # also handles NaN
  2280. else:
  2281. ha = 'right' if dat < 0 else 'left' # also handles NaN
  2282. va = 'center'
  2283. if np.isnan(dat):
  2284. lbl = ''
  2285. if lbl is None:
  2286. if isinstance(fmt, str):
  2287. lbl = cbook._auto_format_str(fmt, value)
  2288. elif callable(fmt):
  2289. lbl = fmt(value)
  2290. else:
  2291. raise TypeError("fmt must be a str or callable")
  2292. annotation = self.annotate(lbl,
  2293. xy, xytext, textcoords="offset points",
  2294. ha=ha, va=va, **kwargs)
  2295. annotations.append(annotation)
  2296. return annotations
  2297. @_preprocess_data()
  2298. @_docstring.dedent_interpd
  2299. def broken_barh(self, xranges, yrange, **kwargs):
  2300. """
  2301. Plot a horizontal sequence of rectangles.
  2302. A rectangle is drawn for each element of *xranges*. All rectangles
  2303. have the same vertical position and size defined by *yrange*.
  2304. Parameters
  2305. ----------
  2306. xranges : sequence of tuples (*xmin*, *xwidth*)
  2307. The x-positions and extents of the rectangles. For each tuple
  2308. (*xmin*, *xwidth*) a rectangle is drawn from *xmin* to *xmin* +
  2309. *xwidth*.
  2310. yrange : (*ymin*, *yheight*)
  2311. The y-position and extent for all the rectangles.
  2312. Returns
  2313. -------
  2314. `~.collections.PolyCollection`
  2315. Other Parameters
  2316. ----------------
  2317. data : indexable object, optional
  2318. DATA_PARAMETER_PLACEHOLDER
  2319. **kwargs : `.PolyCollection` properties
  2320. Each *kwarg* can be either a single argument applying to all
  2321. rectangles, e.g.::
  2322. facecolors='black'
  2323. or a sequence of arguments over which is cycled, e.g.::
  2324. facecolors=('black', 'blue')
  2325. would create interleaving black and blue rectangles.
  2326. Supported keywords:
  2327. %(PolyCollection:kwdoc)s
  2328. """
  2329. # process the unit information
  2330. xdata = cbook._safe_first_finite(xranges) if len(xranges) else None
  2331. ydata = cbook._safe_first_finite(yrange) if len(yrange) else None
  2332. self._process_unit_info(
  2333. [("x", xdata), ("y", ydata)], kwargs, convert=False)
  2334. vertices = []
  2335. y0, dy = yrange
  2336. y0, y1 = self.convert_yunits((y0, y0 + dy))
  2337. for xr in xranges: # convert the absolute values, not the x and dx
  2338. try:
  2339. x0, dx = xr
  2340. except Exception:
  2341. raise ValueError(
  2342. "each range in xrange must be a sequence with two "
  2343. "elements (i.e. xrange must be an (N, 2) array)") from None
  2344. x0, x1 = self.convert_xunits((x0, x0 + dx))
  2345. vertices.append([(x0, y0), (x0, y1), (x1, y1), (x1, y0)])
  2346. col = mcoll.PolyCollection(np.array(vertices), **kwargs)
  2347. self.add_collection(col, autolim=True)
  2348. self._request_autoscale_view()
  2349. return col
  2350. @_preprocess_data()
  2351. def stem(self, *args, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
  2352. label=None, orientation='vertical'):
  2353. """
  2354. Create a stem plot.
  2355. A stem plot draws lines perpendicular to a baseline at each location
  2356. *locs* from the baseline to *heads*, and places a marker there. For
  2357. vertical stem plots (the default), the *locs* are *x* positions, and
  2358. the *heads* are *y* values. For horizontal stem plots, the *locs* are
  2359. *y* positions, and the *heads* are *x* values.
  2360. Call signature::
  2361. stem([locs,] heads, linefmt=None, markerfmt=None, basefmt=None)
  2362. The *locs*-positions are optional. *linefmt* may be provided as
  2363. positional, but all other formats must be provided as keyword
  2364. arguments.
  2365. Parameters
  2366. ----------
  2367. locs : array-like, default: (0, 1, ..., len(heads) - 1)
  2368. For vertical stem plots, the x-positions of the stems.
  2369. For horizontal stem plots, the y-positions of the stems.
  2370. heads : array-like
  2371. For vertical stem plots, the y-values of the stem heads.
  2372. For horizontal stem plots, the x-values of the stem heads.
  2373. linefmt : str, optional
  2374. A string defining the color and/or linestyle of the vertical lines:
  2375. ========= =============
  2376. Character Line Style
  2377. ========= =============
  2378. ``'-'`` solid line
  2379. ``'--'`` dashed line
  2380. ``'-.'`` dash-dot line
  2381. ``':'`` dotted line
  2382. ========= =============
  2383. Default: 'C0-', i.e. solid line with the first color of the color
  2384. cycle.
  2385. Note: Markers specified through this parameter (e.g. 'x') will be
  2386. silently ignored. Instead, markers should be specified using
  2387. *markerfmt*.
  2388. markerfmt : str, optional
  2389. A string defining the color and/or shape of the markers at the stem
  2390. heads. If the marker is not given, use the marker 'o', i.e. filled
  2391. circles. If the color is not given, use the color from *linefmt*.
  2392. basefmt : str, default: 'C3-' ('C2-' in classic mode)
  2393. A format string defining the properties of the baseline.
  2394. orientation : {'vertical', 'horizontal'}, default: 'vertical'
  2395. If 'vertical', will produce a plot with stems oriented vertically,
  2396. If 'horizontal', the stems will be oriented horizontally.
  2397. bottom : float, default: 0
  2398. The y/x-position of the baseline (depending on orientation).
  2399. label : str, default: None
  2400. The label to use for the stems in legends.
  2401. data : indexable object, optional
  2402. DATA_PARAMETER_PLACEHOLDER
  2403. Returns
  2404. -------
  2405. `.StemContainer`
  2406. The container may be treated like a tuple
  2407. (*markerline*, *stemlines*, *baseline*)
  2408. Notes
  2409. -----
  2410. .. seealso::
  2411. The MATLAB function
  2412. `stem <https://www.mathworks.com/help/matlab/ref/stem.html>`_
  2413. which inspired this method.
  2414. """
  2415. if not 1 <= len(args) <= 3:
  2416. raise _api.nargs_error('stem', '1-3', len(args))
  2417. _api.check_in_list(['horizontal', 'vertical'], orientation=orientation)
  2418. if len(args) == 1:
  2419. heads, = args
  2420. locs = np.arange(len(heads))
  2421. args = ()
  2422. elif isinstance(args[1], str):
  2423. heads, *args = args
  2424. locs = np.arange(len(heads))
  2425. else:
  2426. locs, heads, *args = args
  2427. if orientation == 'vertical':
  2428. locs, heads = self._process_unit_info([("x", locs), ("y", heads)])
  2429. else: # horizontal
  2430. heads, locs = self._process_unit_info([("x", heads), ("y", locs)])
  2431. # resolve line format
  2432. if linefmt is None:
  2433. linefmt = args[0] if len(args) > 0 else "C0-"
  2434. linestyle, linemarker, linecolor = _process_plot_format(linefmt)
  2435. # resolve marker format
  2436. if markerfmt is None:
  2437. # if not given as kwarg, fall back to 'o'
  2438. markerfmt = "o"
  2439. if markerfmt == '':
  2440. markerfmt = ' ' # = empty line style; '' would resolve rcParams
  2441. markerstyle, markermarker, markercolor = \
  2442. _process_plot_format(markerfmt)
  2443. if markermarker is None:
  2444. markermarker = 'o'
  2445. if markerstyle is None:
  2446. markerstyle = 'None'
  2447. if markercolor is None:
  2448. markercolor = linecolor
  2449. # resolve baseline format
  2450. if basefmt is None:
  2451. basefmt = ("C2-" if mpl.rcParams["_internal.classic_mode"] else
  2452. "C3-")
  2453. basestyle, basemarker, basecolor = _process_plot_format(basefmt)
  2454. # New behaviour in 3.1 is to use a LineCollection for the stemlines
  2455. if linestyle is None:
  2456. linestyle = mpl.rcParams['lines.linestyle']
  2457. xlines = self.vlines if orientation == "vertical" else self.hlines
  2458. stemlines = xlines(
  2459. locs, bottom, heads,
  2460. colors=linecolor, linestyles=linestyle, label="_nolegend_")
  2461. if orientation == 'horizontal':
  2462. marker_x = heads
  2463. marker_y = locs
  2464. baseline_x = [bottom, bottom]
  2465. baseline_y = [np.min(locs), np.max(locs)]
  2466. else:
  2467. marker_x = locs
  2468. marker_y = heads
  2469. baseline_x = [np.min(locs), np.max(locs)]
  2470. baseline_y = [bottom, bottom]
  2471. markerline, = self.plot(marker_x, marker_y,
  2472. color=markercolor, linestyle=markerstyle,
  2473. marker=markermarker, label="_nolegend_")
  2474. baseline, = self.plot(baseline_x, baseline_y,
  2475. color=basecolor, linestyle=basestyle,
  2476. marker=basemarker, label="_nolegend_")
  2477. stem_container = StemContainer((markerline, stemlines, baseline),
  2478. label=label)
  2479. self.add_container(stem_container)
  2480. return stem_container
  2481. @_preprocess_data(replace_names=["x", "explode", "labels", "colors"])
  2482. def pie(self, x, explode=None, labels=None, colors=None,
  2483. autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
  2484. startangle=0, radius=1, counterclock=True,
  2485. wedgeprops=None, textprops=None, center=(0, 0),
  2486. frame=False, rotatelabels=False, *, normalize=True, hatch=None):
  2487. """
  2488. Plot a pie chart.
  2489. Make a pie chart of array *x*. The fractional area of each wedge is
  2490. given by ``x/sum(x)``.
  2491. The wedges are plotted counterclockwise, by default starting from the
  2492. x-axis.
  2493. Parameters
  2494. ----------
  2495. x : 1D array-like
  2496. The wedge sizes.
  2497. explode : array-like, default: None
  2498. If not *None*, is a ``len(x)`` array which specifies the fraction
  2499. of the radius with which to offset each wedge.
  2500. labels : list, default: None
  2501. A sequence of strings providing the labels for each wedge
  2502. colors : color or array-like of color, default: None
  2503. A sequence of colors through which the pie chart will cycle. If
  2504. *None*, will use the colors in the currently active cycle.
  2505. hatch : str or list, default: None
  2506. Hatching pattern applied to all pie wedges or sequence of patterns
  2507. through which the chart will cycle. For a list of valid patterns,
  2508. see :doc:`/gallery/shapes_and_collections/hatch_style_reference`.
  2509. .. versionadded:: 3.7
  2510. autopct : None or str or callable, default: None
  2511. If not *None*, *autopct* is a string or function used to label the
  2512. wedges with their numeric value. The label will be placed inside
  2513. the wedge. If *autopct* is a format string, the label will be
  2514. ``fmt % pct``. If *autopct* is a function, then it will be called.
  2515. pctdistance : float, default: 0.6
  2516. The relative distance along the radius at which the text
  2517. generated by *autopct* is drawn. To draw the text outside the pie,
  2518. set *pctdistance* > 1. This parameter is ignored if *autopct* is
  2519. ``None``.
  2520. labeldistance : float or None, default: 1.1
  2521. The relative distance along the radius at which the labels are
  2522. drawn. To draw the labels inside the pie, set *labeldistance* < 1.
  2523. If set to ``None``, labels are not drawn but are still stored for
  2524. use in `.legend`.
  2525. shadow : bool or dict, default: False
  2526. If bool, whether to draw a shadow beneath the pie. If dict, draw a shadow
  2527. passing the properties in the dict to `.Shadow`.
  2528. .. versionadded:: 3.8
  2529. *shadow* can be a dict.
  2530. startangle : float, default: 0 degrees
  2531. The angle by which the start of the pie is rotated,
  2532. counterclockwise from the x-axis.
  2533. radius : float, default: 1
  2534. The radius of the pie.
  2535. counterclock : bool, default: True
  2536. Specify fractions direction, clockwise or counterclockwise.
  2537. wedgeprops : dict, default: None
  2538. Dict of arguments passed to each `.patches.Wedge` of the pie.
  2539. For example, ``wedgeprops = {'linewidth': 3}`` sets the width of
  2540. the wedge border lines equal to 3. By default, ``clip_on=False``.
  2541. When there is a conflict between these properties and other
  2542. keywords, properties passed to *wedgeprops* take precedence.
  2543. textprops : dict, default: None
  2544. Dict of arguments to pass to the text objects.
  2545. center : (float, float), default: (0, 0)
  2546. The coordinates of the center of the chart.
  2547. frame : bool, default: False
  2548. Plot Axes frame with the chart if true.
  2549. rotatelabels : bool, default: False
  2550. Rotate each label to the angle of the corresponding slice if true.
  2551. normalize : bool, default: True
  2552. When *True*, always make a full pie by normalizing x so that
  2553. ``sum(x) == 1``. *False* makes a partial pie if ``sum(x) <= 1``
  2554. and raises a `ValueError` for ``sum(x) > 1``.
  2555. data : indexable object, optional
  2556. DATA_PARAMETER_PLACEHOLDER
  2557. Returns
  2558. -------
  2559. patches : list
  2560. A sequence of `matplotlib.patches.Wedge` instances
  2561. texts : list
  2562. A list of the label `.Text` instances.
  2563. autotexts : list
  2564. A list of `.Text` instances for the numeric labels. This will only
  2565. be returned if the parameter *autopct* is not *None*.
  2566. Notes
  2567. -----
  2568. The pie chart will probably look best if the figure and Axes are
  2569. square, or the Axes aspect is equal.
  2570. This method sets the aspect ratio of the axis to "equal".
  2571. The Axes aspect ratio can be controlled with `.Axes.set_aspect`.
  2572. """
  2573. self.set_aspect('equal')
  2574. # The use of float32 is "historical", but can't be changed without
  2575. # regenerating the test baselines.
  2576. x = np.asarray(x, np.float32)
  2577. if x.ndim > 1:
  2578. raise ValueError("x must be 1D")
  2579. if np.any(x < 0):
  2580. raise ValueError("Wedge sizes 'x' must be non negative values")
  2581. sx = x.sum()
  2582. if normalize:
  2583. x = x / sx
  2584. elif sx > 1:
  2585. raise ValueError('Cannot plot an unnormalized pie with sum(x) > 1')
  2586. if labels is None:
  2587. labels = [''] * len(x)
  2588. if explode is None:
  2589. explode = [0] * len(x)
  2590. if len(x) != len(labels):
  2591. raise ValueError("'label' must be of length 'x'")
  2592. if len(x) != len(explode):
  2593. raise ValueError("'explode' must be of length 'x'")
  2594. if colors is None:
  2595. get_next_color = self._get_patches_for_fill.get_next_color
  2596. else:
  2597. color_cycle = itertools.cycle(colors)
  2598. def get_next_color():
  2599. return next(color_cycle)
  2600. hatch_cycle = itertools.cycle(np.atleast_1d(hatch))
  2601. _api.check_isinstance(Real, radius=radius, startangle=startangle)
  2602. if radius <= 0:
  2603. raise ValueError(f'radius must be a positive number, not {radius}')
  2604. # Starting theta1 is the start fraction of the circle
  2605. theta1 = startangle / 360
  2606. if wedgeprops is None:
  2607. wedgeprops = {}
  2608. if textprops is None:
  2609. textprops = {}
  2610. texts = []
  2611. slices = []
  2612. autotexts = []
  2613. for frac, label, expl in zip(x, labels, explode):
  2614. x, y = center
  2615. theta2 = (theta1 + frac) if counterclock else (theta1 - frac)
  2616. thetam = 2 * np.pi * 0.5 * (theta1 + theta2)
  2617. x += expl * math.cos(thetam)
  2618. y += expl * math.sin(thetam)
  2619. w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2),
  2620. 360. * max(theta1, theta2),
  2621. facecolor=get_next_color(),
  2622. hatch=next(hatch_cycle),
  2623. clip_on=False,
  2624. label=label)
  2625. w.set(**wedgeprops)
  2626. slices.append(w)
  2627. self.add_patch(w)
  2628. if shadow:
  2629. # Make sure to add a shadow after the call to add_patch so the
  2630. # figure and transform props will be set.
  2631. shadow_dict = {'ox': -0.02, 'oy': -0.02, 'label': '_nolegend_'}
  2632. if isinstance(shadow, dict):
  2633. shadow_dict.update(shadow)
  2634. self.add_patch(mpatches.Shadow(w, **shadow_dict))
  2635. if labeldistance is not None:
  2636. xt = x + labeldistance * radius * math.cos(thetam)
  2637. yt = y + labeldistance * radius * math.sin(thetam)
  2638. label_alignment_h = 'left' if xt > 0 else 'right'
  2639. label_alignment_v = 'center'
  2640. label_rotation = 'horizontal'
  2641. if rotatelabels:
  2642. label_alignment_v = 'bottom' if yt > 0 else 'top'
  2643. label_rotation = (np.rad2deg(thetam)
  2644. + (0 if xt > 0 else 180))
  2645. t = self.text(xt, yt, label,
  2646. clip_on=False,
  2647. horizontalalignment=label_alignment_h,
  2648. verticalalignment=label_alignment_v,
  2649. rotation=label_rotation,
  2650. size=mpl.rcParams['xtick.labelsize'])
  2651. t.set(**textprops)
  2652. texts.append(t)
  2653. if autopct is not None:
  2654. xt = x + pctdistance * radius * math.cos(thetam)
  2655. yt = y + pctdistance * radius * math.sin(thetam)
  2656. if isinstance(autopct, str):
  2657. s = autopct % (100. * frac)
  2658. elif callable(autopct):
  2659. s = autopct(100. * frac)
  2660. else:
  2661. raise TypeError(
  2662. 'autopct must be callable or a format string')
  2663. t = self.text(xt, yt, s,
  2664. clip_on=False,
  2665. horizontalalignment='center',
  2666. verticalalignment='center')
  2667. t.set(**textprops)
  2668. autotexts.append(t)
  2669. theta1 = theta2
  2670. if frame:
  2671. self._request_autoscale_view()
  2672. else:
  2673. self.set(frame_on=False, xticks=[], yticks=[],
  2674. xlim=(-1.25 + center[0], 1.25 + center[0]),
  2675. ylim=(-1.25 + center[1], 1.25 + center[1]))
  2676. if autopct is None:
  2677. return slices, texts
  2678. else:
  2679. return slices, texts, autotexts
  2680. @staticmethod
  2681. def _errorevery_to_mask(x, errorevery):
  2682. """
  2683. Normalize `errorbar`'s *errorevery* to be a boolean mask for data *x*.
  2684. This function is split out to be usable both by 2D and 3D errorbars.
  2685. """
  2686. if isinstance(errorevery, Integral):
  2687. errorevery = (0, errorevery)
  2688. if isinstance(errorevery, tuple):
  2689. if (len(errorevery) == 2 and
  2690. isinstance(errorevery[0], Integral) and
  2691. isinstance(errorevery[1], Integral)):
  2692. errorevery = slice(errorevery[0], None, errorevery[1])
  2693. else:
  2694. raise ValueError(
  2695. f'{errorevery=!r} is a not a tuple of two integers')
  2696. elif isinstance(errorevery, slice):
  2697. pass
  2698. elif not isinstance(errorevery, str) and np.iterable(errorevery):
  2699. try:
  2700. x[errorevery] # fancy indexing
  2701. except (ValueError, IndexError) as err:
  2702. raise ValueError(
  2703. f"{errorevery=!r} is iterable but not a valid NumPy fancy "
  2704. "index to match 'xerr'/'yerr'") from err
  2705. else:
  2706. raise ValueError(f"{errorevery=!r} is not a recognized value")
  2707. everymask = np.zeros(len(x), bool)
  2708. everymask[errorevery] = True
  2709. return everymask
  2710. @_preprocess_data(replace_names=["x", "y", "xerr", "yerr"],
  2711. label_namer="y")
  2712. @_docstring.dedent_interpd
  2713. def errorbar(self, x, y, yerr=None, xerr=None,
  2714. fmt='', ecolor=None, elinewidth=None, capsize=None,
  2715. barsabove=False, lolims=False, uplims=False,
  2716. xlolims=False, xuplims=False, errorevery=1, capthick=None,
  2717. **kwargs):
  2718. """
  2719. Plot y versus x as lines and/or markers with attached errorbars.
  2720. *x*, *y* define the data locations, *xerr*, *yerr* define the errorbar
  2721. sizes. By default, this draws the data markers/lines as well as the
  2722. errorbars. Use fmt='none' to draw errorbars without any data markers.
  2723. .. versionadded:: 3.7
  2724. Caps and error lines are drawn in polar coordinates on polar plots.
  2725. Parameters
  2726. ----------
  2727. x, y : float or array-like
  2728. The data positions.
  2729. xerr, yerr : float or array-like, shape(N,) or shape(2, N), optional
  2730. The errorbar sizes:
  2731. - scalar: Symmetric +/- values for all data points.
  2732. - shape(N,): Symmetric +/-values for each data point.
  2733. - shape(2, N): Separate - and + values for each bar. First row
  2734. contains the lower errors, the second row contains the upper
  2735. errors.
  2736. - *None*: No errorbar.
  2737. All values must be >= 0.
  2738. See :doc:`/gallery/statistics/errorbar_features`
  2739. for an example on the usage of ``xerr`` and ``yerr``.
  2740. fmt : str, default: ''
  2741. The format for the data points / data lines. See `.plot` for
  2742. details.
  2743. Use 'none' (case-insensitive) to plot errorbars without any data
  2744. markers.
  2745. ecolor : color, default: None
  2746. The color of the errorbar lines. If None, use the color of the
  2747. line connecting the markers.
  2748. elinewidth : float, default: None
  2749. The linewidth of the errorbar lines. If None, the linewidth of
  2750. the current style is used.
  2751. capsize : float, default: :rc:`errorbar.capsize`
  2752. The length of the error bar caps in points.
  2753. capthick : float, default: None
  2754. An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*).
  2755. This setting is a more sensible name for the property that
  2756. controls the thickness of the error bar cap in points. For
  2757. backwards compatibility, if *mew* or *markeredgewidth* are given,
  2758. then they will over-ride *capthick*. This may change in future
  2759. releases.
  2760. barsabove : bool, default: False
  2761. If True, will plot the errorbars above the plot
  2762. symbols. Default is below.
  2763. lolims, uplims, xlolims, xuplims : bool or array-like, default: False
  2764. These arguments can be used to indicate that a value gives only
  2765. upper/lower limits. In that case a caret symbol is used to
  2766. indicate this. *lims*-arguments may be scalars, or array-likes of
  2767. the same length as *xerr* and *yerr*. To use limits with inverted
  2768. axes, `~.Axes.set_xlim` or `~.Axes.set_ylim` must be called before
  2769. :meth:`errorbar`. Note the tricky parameter names: setting e.g.
  2770. *lolims* to True means that the y-value is a *lower* limit of the
  2771. True value, so, only an *upward*-pointing arrow will be drawn!
  2772. errorevery : int or (int, int), default: 1
  2773. draws error bars on a subset of the data. *errorevery* =N draws
  2774. error bars on the points (x[::N], y[::N]).
  2775. *errorevery* =(start, N) draws error bars on the points
  2776. (x[start::N], y[start::N]). e.g. errorevery=(6, 3)
  2777. adds error bars to the data at (x[6], x[9], x[12], x[15], ...).
  2778. Used to avoid overlapping error bars when two series share x-axis
  2779. values.
  2780. Returns
  2781. -------
  2782. `.ErrorbarContainer`
  2783. The container contains:
  2784. - plotline: `~matplotlib.lines.Line2D` instance of x, y plot markers
  2785. and/or line.
  2786. - caplines: A tuple of `~matplotlib.lines.Line2D` instances of the error
  2787. bar caps.
  2788. - barlinecols: A tuple of `.LineCollection` with the horizontal and
  2789. vertical error ranges.
  2790. Other Parameters
  2791. ----------------
  2792. data : indexable object, optional
  2793. DATA_PARAMETER_PLACEHOLDER
  2794. **kwargs
  2795. All other keyword arguments are passed on to the `~.Axes.plot` call
  2796. drawing the markers. For example, this code makes big red squares
  2797. with thick green edges::
  2798. x, y, yerr = rand(3, 10)
  2799. errorbar(x, y, yerr, marker='s', mfc='red',
  2800. mec='green', ms=20, mew=4)
  2801. where *mfc*, *mec*, *ms* and *mew* are aliases for the longer
  2802. property names, *markerfacecolor*, *markeredgecolor*, *markersize*
  2803. and *markeredgewidth*.
  2804. Valid kwargs for the marker properties are:
  2805. - *dashes*
  2806. - *dash_capstyle*
  2807. - *dash_joinstyle*
  2808. - *drawstyle*
  2809. - *fillstyle*
  2810. - *linestyle*
  2811. - *marker*
  2812. - *markeredgecolor*
  2813. - *markeredgewidth*
  2814. - *markerfacecolor*
  2815. - *markerfacecoloralt*
  2816. - *markersize*
  2817. - *markevery*
  2818. - *solid_capstyle*
  2819. - *solid_joinstyle*
  2820. Refer to the corresponding `.Line2D` property for more details:
  2821. %(Line2D:kwdoc)s
  2822. """
  2823. kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
  2824. # Drop anything that comes in as None to use the default instead.
  2825. kwargs = {k: v for k, v in kwargs.items() if v is not None}
  2826. kwargs.setdefault('zorder', 2)
  2827. # Casting to object arrays preserves units.
  2828. if not isinstance(x, np.ndarray):
  2829. x = np.asarray(x, dtype=object)
  2830. if not isinstance(y, np.ndarray):
  2831. y = np.asarray(y, dtype=object)
  2832. def _upcast_err(err):
  2833. """
  2834. Safely handle tuple of containers that carry units.
  2835. This function covers the case where the input to the xerr/yerr is a
  2836. length 2 tuple of equal length ndarray-subclasses that carry the
  2837. unit information in the container.
  2838. If we have a tuple of nested numpy array (subclasses), we defer
  2839. coercing the units to be consistent to the underlying unit
  2840. library (and implicitly the broadcasting).
  2841. Otherwise, fallback to casting to an object array.
  2842. """
  2843. if (
  2844. # make sure it is not a scalar
  2845. np.iterable(err) and
  2846. # and it is not empty
  2847. len(err) > 0 and
  2848. # and the first element is an array sub-class use
  2849. # safe_first_element because getitem is index-first not
  2850. # location first on pandas objects so err[0] almost always
  2851. # fails.
  2852. isinstance(cbook._safe_first_finite(err), np.ndarray)
  2853. ):
  2854. # Get the type of the first element
  2855. atype = type(cbook._safe_first_finite(err))
  2856. # Promote the outer container to match the inner container
  2857. if atype is np.ndarray:
  2858. # Converts using np.asarray, because data cannot
  2859. # be directly passed to init of np.ndarray
  2860. return np.asarray(err, dtype=object)
  2861. # If atype is not np.ndarray, directly pass data to init.
  2862. # This works for types such as unyts and astropy units
  2863. return atype(err)
  2864. # Otherwise wrap it in an object array
  2865. return np.asarray(err, dtype=object)
  2866. if xerr is not None and not isinstance(xerr, np.ndarray):
  2867. xerr = _upcast_err(xerr)
  2868. if yerr is not None and not isinstance(yerr, np.ndarray):
  2869. yerr = _upcast_err(yerr)
  2870. x, y = np.atleast_1d(x, y) # Make sure all the args are iterable.
  2871. if len(x) != len(y):
  2872. raise ValueError("'x' and 'y' must have the same size")
  2873. everymask = self._errorevery_to_mask(x, errorevery)
  2874. label = kwargs.pop("label", None)
  2875. kwargs['label'] = '_nolegend_'
  2876. # Create the main line and determine overall kwargs for child artists.
  2877. # We avoid calling self.plot() directly, or self._get_lines(), because
  2878. # that would call self._process_unit_info again, and do other indirect
  2879. # data processing.
  2880. (data_line, base_style), = self._get_lines._plot_args(
  2881. self, (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True)
  2882. # Do this after creating `data_line` to avoid modifying `base_style`.
  2883. if barsabove:
  2884. data_line.set_zorder(kwargs['zorder'] - .1)
  2885. else:
  2886. data_line.set_zorder(kwargs['zorder'] + .1)
  2887. # Add line to plot, or throw it away and use it to determine kwargs.
  2888. if fmt.lower() != 'none':
  2889. self.add_line(data_line)
  2890. else:
  2891. data_line = None
  2892. # Remove alpha=0 color that _get_lines._plot_args returns for
  2893. # 'none' format, and replace it with user-specified color, if
  2894. # supplied.
  2895. base_style.pop('color')
  2896. if 'color' in kwargs:
  2897. base_style['color'] = kwargs.pop('color')
  2898. if 'color' not in base_style:
  2899. base_style['color'] = 'C0'
  2900. if ecolor is None:
  2901. ecolor = base_style['color']
  2902. # Eject any line-specific information from format string, as it's not
  2903. # needed for bars or caps.
  2904. for key in ['marker', 'markersize', 'markerfacecolor',
  2905. 'markerfacecoloralt',
  2906. 'markeredgewidth', 'markeredgecolor', 'markevery',
  2907. 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle',
  2908. 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle',
  2909. 'dashes']:
  2910. base_style.pop(key, None)
  2911. # Make the style dict for the line collections (the bars).
  2912. eb_lines_style = {**base_style, 'color': ecolor}
  2913. if elinewidth is not None:
  2914. eb_lines_style['linewidth'] = elinewidth
  2915. elif 'linewidth' in kwargs:
  2916. eb_lines_style['linewidth'] = kwargs['linewidth']
  2917. for key in ('transform', 'alpha', 'zorder', 'rasterized'):
  2918. if key in kwargs:
  2919. eb_lines_style[key] = kwargs[key]
  2920. # Make the style dict for caps (the "hats").
  2921. eb_cap_style = {**base_style, 'linestyle': 'none'}
  2922. if capsize is None:
  2923. capsize = mpl.rcParams["errorbar.capsize"]
  2924. if capsize > 0:
  2925. eb_cap_style['markersize'] = 2. * capsize
  2926. if capthick is not None:
  2927. eb_cap_style['markeredgewidth'] = capthick
  2928. # For backwards-compat, allow explicit setting of
  2929. # 'markeredgewidth' to over-ride capthick.
  2930. for key in ('markeredgewidth', 'transform', 'alpha',
  2931. 'zorder', 'rasterized'):
  2932. if key in kwargs:
  2933. eb_cap_style[key] = kwargs[key]
  2934. eb_cap_style['color'] = ecolor
  2935. barcols = []
  2936. caplines = {'x': [], 'y': []}
  2937. # Vectorized fancy-indexer.
  2938. def apply_mask(arrays, mask):
  2939. return [array[mask] for array in arrays]
  2940. # dep: dependent dataset, indep: independent dataset
  2941. for (dep_axis, dep, err, lolims, uplims, indep, lines_func,
  2942. marker, lomarker, himarker) in [
  2943. ("x", x, xerr, xlolims, xuplims, y, self.hlines,
  2944. "|", mlines.CARETRIGHTBASE, mlines.CARETLEFTBASE),
  2945. ("y", y, yerr, lolims, uplims, x, self.vlines,
  2946. "_", mlines.CARETUPBASE, mlines.CARETDOWNBASE),
  2947. ]:
  2948. if err is None:
  2949. continue
  2950. lolims = np.broadcast_to(lolims, len(dep)).astype(bool)
  2951. uplims = np.broadcast_to(uplims, len(dep)).astype(bool)
  2952. try:
  2953. np.broadcast_to(err, (2, len(dep)))
  2954. except ValueError:
  2955. raise ValueError(
  2956. f"'{dep_axis}err' (shape: {np.shape(err)}) must be a "
  2957. f"scalar or a 1D or (2, n) array-like whose shape matches "
  2958. f"'{dep_axis}' (shape: {np.shape(dep)})") from None
  2959. res = np.zeros(err.shape, dtype=bool) # Default in case of nan
  2960. if np.any(np.less(err, -err, out=res, where=(err == err))):
  2961. # like err<0, but also works for timedelta and nan.
  2962. raise ValueError(
  2963. f"'{dep_axis}err' must not contain negative values")
  2964. # This is like
  2965. # elow, ehigh = np.broadcast_to(...)
  2966. # return dep - elow * ~lolims, dep + ehigh * ~uplims
  2967. # except that broadcast_to would strip units.
  2968. low, high = dep + np.vstack([-(1 - lolims), 1 - uplims]) * err
  2969. barcols.append(lines_func(
  2970. *apply_mask([indep, low, high], everymask), **eb_lines_style))
  2971. if self.name == "polar" and dep_axis == "x":
  2972. for b in barcols:
  2973. for p in b.get_paths():
  2974. p._interpolation_steps = 2
  2975. # Normal errorbars for points without upper/lower limits.
  2976. nolims = ~(lolims | uplims)
  2977. if nolims.any() and capsize > 0:
  2978. indep_masked, lo_masked, hi_masked = apply_mask(
  2979. [indep, low, high], nolims & everymask)
  2980. for lh_masked in [lo_masked, hi_masked]:
  2981. # Since this has to work for x and y as dependent data, we
  2982. # first set both x and y to the independent variable and
  2983. # overwrite the respective dependent data in a second step.
  2984. line = mlines.Line2D(indep_masked, indep_masked,
  2985. marker=marker, **eb_cap_style)
  2986. line.set(**{f"{dep_axis}data": lh_masked})
  2987. caplines[dep_axis].append(line)
  2988. for idx, (lims, hl) in enumerate([(lolims, high), (uplims, low)]):
  2989. if not lims.any():
  2990. continue
  2991. hlmarker = (
  2992. himarker
  2993. if self._axis_map[dep_axis].get_inverted() ^ idx
  2994. else lomarker)
  2995. x_masked, y_masked, hl_masked = apply_mask(
  2996. [x, y, hl], lims & everymask)
  2997. # As above, we set the dependent data in a second step.
  2998. line = mlines.Line2D(x_masked, y_masked,
  2999. marker=hlmarker, **eb_cap_style)
  3000. line.set(**{f"{dep_axis}data": hl_masked})
  3001. caplines[dep_axis].append(line)
  3002. if capsize > 0:
  3003. caplines[dep_axis].append(mlines.Line2D(
  3004. x_masked, y_masked, marker=marker, **eb_cap_style))
  3005. if self.name == 'polar':
  3006. for axis in caplines:
  3007. for l in caplines[axis]:
  3008. # Rotate caps to be perpendicular to the error bars
  3009. for theta, r in zip(l.get_xdata(), l.get_ydata()):
  3010. rotation = mtransforms.Affine2D().rotate(theta)
  3011. if axis == 'y':
  3012. rotation.rotate(-np.pi / 2)
  3013. ms = mmarkers.MarkerStyle(marker=marker,
  3014. transform=rotation)
  3015. self.add_line(mlines.Line2D([theta], [r], marker=ms,
  3016. **eb_cap_style))
  3017. else:
  3018. for axis in caplines:
  3019. for l in caplines[axis]:
  3020. self.add_line(l)
  3021. self._request_autoscale_view()
  3022. caplines = caplines['x'] + caplines['y']
  3023. errorbar_container = ErrorbarContainer(
  3024. (data_line, tuple(caplines), tuple(barcols)),
  3025. has_xerr=(xerr is not None), has_yerr=(yerr is not None),
  3026. label=label)
  3027. self.containers.append(errorbar_container)
  3028. return errorbar_container # (l0, caplines, barcols)
  3029. @_preprocess_data()
  3030. def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
  3031. positions=None, widths=None, patch_artist=None,
  3032. bootstrap=None, usermedians=None, conf_intervals=None,
  3033. meanline=None, showmeans=None, showcaps=None,
  3034. showbox=None, showfliers=None, boxprops=None,
  3035. labels=None, flierprops=None, medianprops=None,
  3036. meanprops=None, capprops=None, whiskerprops=None,
  3037. manage_ticks=True, autorange=False, zorder=None,
  3038. capwidths=None):
  3039. """
  3040. Draw a box and whisker plot.
  3041. The box extends from the first quartile (Q1) to the third
  3042. quartile (Q3) of the data, with a line at the median.
  3043. The whiskers extend from the box to the farthest data point
  3044. lying within 1.5x the inter-quartile range (IQR) from the box.
  3045. Flier points are those past the end of the whiskers.
  3046. See https://en.wikipedia.org/wiki/Box_plot for reference.
  3047. .. code-block:: none
  3048. Q1-1.5IQR Q1 median Q3 Q3+1.5IQR
  3049. |-----:-----|
  3050. o |--------| : |--------| o o
  3051. |-----:-----|
  3052. flier <-----------> fliers
  3053. IQR
  3054. Parameters
  3055. ----------
  3056. x : Array or a sequence of vectors.
  3057. The input data. If a 2D array, a boxplot is drawn for each column
  3058. in *x*. If a sequence of 1D arrays, a boxplot is drawn for each
  3059. array in *x*.
  3060. notch : bool, default: False
  3061. Whether to draw a notched boxplot (`True`), or a rectangular
  3062. boxplot (`False`). The notches represent the confidence interval
  3063. (CI) around the median. The documentation for *bootstrap*
  3064. describes how the locations of the notches are computed by
  3065. default, but their locations may also be overridden by setting the
  3066. *conf_intervals* parameter.
  3067. .. note::
  3068. In cases where the values of the CI are less than the
  3069. lower quartile or greater than the upper quartile, the
  3070. notches will extend beyond the box, giving it a
  3071. distinctive "flipped" appearance. This is expected
  3072. behavior and consistent with other statistical
  3073. visualization packages.
  3074. sym : str, optional
  3075. The default symbol for flier points. An empty string ('') hides
  3076. the fliers. If `None`, then the fliers default to 'b+'. More
  3077. control is provided by the *flierprops* parameter.
  3078. vert : bool, default: True
  3079. If `True`, draws vertical boxes.
  3080. If `False`, draw horizontal boxes.
  3081. whis : float or (float, float), default: 1.5
  3082. The position of the whiskers.
  3083. If a float, the lower whisker is at the lowest datum above
  3084. ``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum
  3085. below ``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and
  3086. third quartiles. The default value of ``whis = 1.5`` corresponds
  3087. to Tukey's original definition of boxplots.
  3088. If a pair of floats, they indicate the percentiles at which to
  3089. draw the whiskers (e.g., (5, 95)). In particular, setting this to
  3090. (0, 100) results in whiskers covering the whole range of the data.
  3091. In the edge case where ``Q1 == Q3``, *whis* is automatically set
  3092. to (0, 100) (cover the whole range of the data) if *autorange* is
  3093. True.
  3094. Beyond the whiskers, data are considered outliers and are plotted
  3095. as individual points.
  3096. bootstrap : int, optional
  3097. Specifies whether to bootstrap the confidence intervals
  3098. around the median for notched boxplots. If *bootstrap* is
  3099. None, no bootstrapping is performed, and notches are
  3100. calculated using a Gaussian-based asymptotic approximation
  3101. (see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and
  3102. Kendall and Stuart, 1967). Otherwise, bootstrap specifies
  3103. the number of times to bootstrap the median to determine its
  3104. 95% confidence intervals. Values between 1000 and 10000 are
  3105. recommended.
  3106. usermedians : 1D array-like, optional
  3107. A 1D array-like of length ``len(x)``. Each entry that is not
  3108. `None` forces the value of the median for the corresponding
  3109. dataset. For entries that are `None`, the medians are computed
  3110. by Matplotlib as normal.
  3111. conf_intervals : array-like, optional
  3112. A 2D array-like of shape ``(len(x), 2)``. Each entry that is not
  3113. None forces the location of the corresponding notch (which is
  3114. only drawn if *notch* is `True`). For entries that are `None`,
  3115. the notches are computed by the method specified by the other
  3116. parameters (e.g., *bootstrap*).
  3117. positions : array-like, optional
  3118. The positions of the boxes. The ticks and limits are
  3119. automatically set to match the positions. Defaults to
  3120. ``range(1, N+1)`` where N is the number of boxes to be drawn.
  3121. widths : float or array-like
  3122. The widths of the boxes. The default is 0.5, or ``0.15*(distance
  3123. between extreme positions)``, if that is smaller.
  3124. patch_artist : bool, default: False
  3125. If `False` produces boxes with the Line2D artist. Otherwise,
  3126. boxes are drawn with Patch artists.
  3127. labels : sequence, optional
  3128. Labels for each dataset (one per dataset).
  3129. manage_ticks : bool, default: True
  3130. If True, the tick locations and labels will be adjusted to match
  3131. the boxplot positions.
  3132. autorange : bool, default: False
  3133. When `True` and the data are distributed such that the 25th and
  3134. 75th percentiles are equal, *whis* is set to (0, 100) such
  3135. that the whisker ends are at the minimum and maximum of the data.
  3136. meanline : bool, default: False
  3137. If `True` (and *showmeans* is `True`), will try to render the
  3138. mean as a line spanning the full width of the box according to
  3139. *meanprops* (see below). Not recommended if *shownotches* is also
  3140. True. Otherwise, means will be shown as points.
  3141. zorder : float, default: ``Line2D.zorder = 2``
  3142. The zorder of the boxplot.
  3143. Returns
  3144. -------
  3145. dict
  3146. A dictionary mapping each component of the boxplot to a list
  3147. of the `.Line2D` instances created. That dictionary has the
  3148. following keys (assuming vertical boxplots):
  3149. - ``boxes``: the main body of the boxplot showing the
  3150. quartiles and the median's confidence intervals if
  3151. enabled.
  3152. - ``medians``: horizontal lines at the median of each box.
  3153. - ``whiskers``: the vertical lines extending to the most
  3154. extreme, non-outlier data points.
  3155. - ``caps``: the horizontal lines at the ends of the
  3156. whiskers.
  3157. - ``fliers``: points representing data that extend beyond
  3158. the whiskers (fliers).
  3159. - ``means``: points or lines representing the means.
  3160. Other Parameters
  3161. ----------------
  3162. showcaps : bool, default: True
  3163. Show the caps on the ends of whiskers.
  3164. showbox : bool, default: True
  3165. Show the central box.
  3166. showfliers : bool, default: True
  3167. Show the outliers beyond the caps.
  3168. showmeans : bool, default: False
  3169. Show the arithmetic means.
  3170. capprops : dict, default: None
  3171. The style of the caps.
  3172. capwidths : float or array, default: None
  3173. The widths of the caps.
  3174. boxprops : dict, default: None
  3175. The style of the box.
  3176. whiskerprops : dict, default: None
  3177. The style of the whiskers.
  3178. flierprops : dict, default: None
  3179. The style of the fliers.
  3180. medianprops : dict, default: None
  3181. The style of the median.
  3182. meanprops : dict, default: None
  3183. The style of the mean.
  3184. data : indexable object, optional
  3185. DATA_PARAMETER_PLACEHOLDER
  3186. See Also
  3187. --------
  3188. violinplot : Draw an estimate of the probability density function.
  3189. """
  3190. # Missing arguments default to rcParams.
  3191. if whis is None:
  3192. whis = mpl.rcParams['boxplot.whiskers']
  3193. if bootstrap is None:
  3194. bootstrap = mpl.rcParams['boxplot.bootstrap']
  3195. bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap,
  3196. labels=labels, autorange=autorange)
  3197. if notch is None:
  3198. notch = mpl.rcParams['boxplot.notch']
  3199. if vert is None:
  3200. vert = mpl.rcParams['boxplot.vertical']
  3201. if patch_artist is None:
  3202. patch_artist = mpl.rcParams['boxplot.patchartist']
  3203. if meanline is None:
  3204. meanline = mpl.rcParams['boxplot.meanline']
  3205. if showmeans is None:
  3206. showmeans = mpl.rcParams['boxplot.showmeans']
  3207. if showcaps is None:
  3208. showcaps = mpl.rcParams['boxplot.showcaps']
  3209. if showbox is None:
  3210. showbox = mpl.rcParams['boxplot.showbox']
  3211. if showfliers is None:
  3212. showfliers = mpl.rcParams['boxplot.showfliers']
  3213. if boxprops is None:
  3214. boxprops = {}
  3215. if whiskerprops is None:
  3216. whiskerprops = {}
  3217. if capprops is None:
  3218. capprops = {}
  3219. if medianprops is None:
  3220. medianprops = {}
  3221. if meanprops is None:
  3222. meanprops = {}
  3223. if flierprops is None:
  3224. flierprops = {}
  3225. if patch_artist:
  3226. boxprops['linestyle'] = 'solid' # Not consistent with bxp.
  3227. if 'color' in boxprops:
  3228. boxprops['edgecolor'] = boxprops.pop('color')
  3229. # if non-default sym value, put it into the flier dictionary
  3230. # the logic for providing the default symbol ('b+') now lives
  3231. # in bxp in the initial value of flierkw
  3232. # handle all of the *sym* related logic here so we only have to pass
  3233. # on the flierprops dict.
  3234. if sym is not None:
  3235. # no-flier case, which should really be done with
  3236. # 'showfliers=False' but none-the-less deal with it to keep back
  3237. # compatibility
  3238. if sym == '':
  3239. # blow away existing dict and make one for invisible markers
  3240. flierprops = dict(linestyle='none', marker='', color='none')
  3241. # turn the fliers off just to be safe
  3242. showfliers = False
  3243. # now process the symbol string
  3244. else:
  3245. # process the symbol string
  3246. # discarded linestyle
  3247. _, marker, color = _process_plot_format(sym)
  3248. # if we have a marker, use it
  3249. if marker is not None:
  3250. flierprops['marker'] = marker
  3251. # if we have a color, use it
  3252. if color is not None:
  3253. # assume that if color is passed in the user want
  3254. # filled symbol, if the users want more control use
  3255. # flierprops
  3256. flierprops['color'] = color
  3257. flierprops['markerfacecolor'] = color
  3258. flierprops['markeredgecolor'] = color
  3259. # replace medians if necessary:
  3260. if usermedians is not None:
  3261. if (len(np.ravel(usermedians)) != len(bxpstats) or
  3262. np.shape(usermedians)[0] != len(bxpstats)):
  3263. raise ValueError(
  3264. "'usermedians' and 'x' have different lengths")
  3265. else:
  3266. # reassign medians as necessary
  3267. for stats, med in zip(bxpstats, usermedians):
  3268. if med is not None:
  3269. stats['med'] = med
  3270. if conf_intervals is not None:
  3271. if len(conf_intervals) != len(bxpstats):
  3272. raise ValueError(
  3273. "'conf_intervals' and 'x' have different lengths")
  3274. else:
  3275. for stats, ci in zip(bxpstats, conf_intervals):
  3276. if ci is not None:
  3277. if len(ci) != 2:
  3278. raise ValueError('each confidence interval must '
  3279. 'have two values')
  3280. else:
  3281. if ci[0] is not None:
  3282. stats['cilo'] = ci[0]
  3283. if ci[1] is not None:
  3284. stats['cihi'] = ci[1]
  3285. artists = self.bxp(bxpstats, positions=positions, widths=widths,
  3286. vert=vert, patch_artist=patch_artist,
  3287. shownotches=notch, showmeans=showmeans,
  3288. showcaps=showcaps, showbox=showbox,
  3289. boxprops=boxprops, flierprops=flierprops,
  3290. medianprops=medianprops, meanprops=meanprops,
  3291. meanline=meanline, showfliers=showfliers,
  3292. capprops=capprops, whiskerprops=whiskerprops,
  3293. manage_ticks=manage_ticks, zorder=zorder,
  3294. capwidths=capwidths)
  3295. return artists
  3296. def bxp(self, bxpstats, positions=None, widths=None, vert=True,
  3297. patch_artist=False, shownotches=False, showmeans=False,
  3298. showcaps=True, showbox=True, showfliers=True,
  3299. boxprops=None, whiskerprops=None, flierprops=None,
  3300. medianprops=None, capprops=None, meanprops=None,
  3301. meanline=False, manage_ticks=True, zorder=None,
  3302. capwidths=None):
  3303. """
  3304. Drawing function for box and whisker plots.
  3305. Make a box and whisker plot for each column of *x* or each
  3306. vector in sequence *x*. The box extends from the lower to
  3307. upper quartile values of the data, with a line at the median.
  3308. The whiskers extend from the box to show the range of the
  3309. data. Flier points are those past the end of the whiskers.
  3310. Parameters
  3311. ----------
  3312. bxpstats : list of dicts
  3313. A list of dictionaries containing stats for each boxplot.
  3314. Required keys are:
  3315. - ``med``: Median (scalar).
  3316. - ``q1``, ``q3``: First & third quartiles (scalars).
  3317. - ``whislo``, ``whishi``: Lower & upper whisker positions (scalars).
  3318. Optional keys are:
  3319. - ``mean``: Mean (scalar). Needed if ``showmeans=True``.
  3320. - ``fliers``: Data beyond the whiskers (array-like).
  3321. Needed if ``showfliers=True``.
  3322. - ``cilo``, ``cihi``: Lower & upper confidence intervals
  3323. about the median. Needed if ``shownotches=True``.
  3324. - ``label``: Name of the dataset (str). If available,
  3325. this will be used a tick label for the boxplot
  3326. positions : array-like, default: [1, 2, ..., n]
  3327. The positions of the boxes. The ticks and limits
  3328. are automatically set to match the positions.
  3329. widths : float or array-like, default: None
  3330. The widths of the boxes. The default is
  3331. ``clip(0.15*(distance between extreme positions), 0.15, 0.5)``.
  3332. capwidths : float or array-like, default: None
  3333. Either a scalar or a vector and sets the width of each cap.
  3334. The default is ``0.5*(width of the box)``, see *widths*.
  3335. vert : bool, default: True
  3336. If `True` (default), makes the boxes vertical.
  3337. If `False`, makes horizontal boxes.
  3338. patch_artist : bool, default: False
  3339. If `False` produces boxes with the `.Line2D` artist.
  3340. If `True` produces boxes with the `~matplotlib.patches.Patch` artist.
  3341. shownotches, showmeans, showcaps, showbox, showfliers : bool
  3342. Whether to draw the CI notches, the mean value (both default to
  3343. False), the caps, the box, and the fliers (all three default to
  3344. True).
  3345. boxprops, whiskerprops, capprops, flierprops, medianprops, meanprops :\
  3346. dict, optional
  3347. Artist properties for the boxes, whiskers, caps, fliers, medians, and
  3348. means.
  3349. meanline : bool, default: False
  3350. If `True` (and *showmeans* is `True`), will try to render the mean
  3351. as a line spanning the full width of the box according to
  3352. *meanprops*. Not recommended if *shownotches* is also True.
  3353. Otherwise, means will be shown as points.
  3354. manage_ticks : bool, default: True
  3355. If True, the tick locations and labels will be adjusted to match the
  3356. boxplot positions.
  3357. zorder : float, default: ``Line2D.zorder = 2``
  3358. The zorder of the resulting boxplot.
  3359. Returns
  3360. -------
  3361. dict
  3362. A dictionary mapping each component of the boxplot to a list
  3363. of the `.Line2D` instances created. That dictionary has the
  3364. following keys (assuming vertical boxplots):
  3365. - ``boxes``: main bodies of the boxplot showing the quartiles, and
  3366. the median's confidence intervals if enabled.
  3367. - ``medians``: horizontal lines at the median of each box.
  3368. - ``whiskers``: vertical lines up to the last non-outlier data.
  3369. - ``caps``: horizontal lines at the ends of the whiskers.
  3370. - ``fliers``: points representing data beyond the whiskers (fliers).
  3371. - ``means``: points or lines representing the means.
  3372. Examples
  3373. --------
  3374. .. plot:: gallery/statistics/bxp.py
  3375. """
  3376. # Clamp median line to edge of box by default.
  3377. medianprops = {
  3378. "solid_capstyle": "butt",
  3379. "dash_capstyle": "butt",
  3380. **(medianprops or {}),
  3381. }
  3382. meanprops = {
  3383. "solid_capstyle": "butt",
  3384. "dash_capstyle": "butt",
  3385. **(meanprops or {}),
  3386. }
  3387. # lists of artists to be output
  3388. whiskers = []
  3389. caps = []
  3390. boxes = []
  3391. medians = []
  3392. means = []
  3393. fliers = []
  3394. # empty list of xticklabels
  3395. datalabels = []
  3396. # Use default zorder if none specified
  3397. if zorder is None:
  3398. zorder = mlines.Line2D.zorder
  3399. zdelta = 0.1
  3400. def merge_kw_rc(subkey, explicit, zdelta=0, usemarker=True):
  3401. d = {k.split('.')[-1]: v for k, v in mpl.rcParams.items()
  3402. if k.startswith(f'boxplot.{subkey}props')}
  3403. d['zorder'] = zorder + zdelta
  3404. if not usemarker:
  3405. d['marker'] = ''
  3406. d.update(cbook.normalize_kwargs(explicit, mlines.Line2D))
  3407. return d
  3408. box_kw = {
  3409. 'linestyle': mpl.rcParams['boxplot.boxprops.linestyle'],
  3410. 'linewidth': mpl.rcParams['boxplot.boxprops.linewidth'],
  3411. 'edgecolor': mpl.rcParams['boxplot.boxprops.color'],
  3412. 'facecolor': ('white' if mpl.rcParams['_internal.classic_mode']
  3413. else mpl.rcParams['patch.facecolor']),
  3414. 'zorder': zorder,
  3415. **cbook.normalize_kwargs(boxprops, mpatches.PathPatch)
  3416. } if patch_artist else merge_kw_rc('box', boxprops, usemarker=False)
  3417. whisker_kw = merge_kw_rc('whisker', whiskerprops, usemarker=False)
  3418. cap_kw = merge_kw_rc('cap', capprops, usemarker=False)
  3419. flier_kw = merge_kw_rc('flier', flierprops)
  3420. median_kw = merge_kw_rc('median', medianprops, zdelta, usemarker=False)
  3421. mean_kw = merge_kw_rc('mean', meanprops, zdelta)
  3422. removed_prop = 'marker' if meanline else 'linestyle'
  3423. # Only remove the property if it's not set explicitly as a parameter.
  3424. if meanprops is None or removed_prop not in meanprops:
  3425. mean_kw[removed_prop] = ''
  3426. # vertical or horizontal plot?
  3427. maybe_swap = slice(None) if vert else slice(None, None, -1)
  3428. def do_plot(xs, ys, **kwargs):
  3429. return self.plot(*[xs, ys][maybe_swap], **kwargs)[0]
  3430. def do_patch(xs, ys, **kwargs):
  3431. path = mpath.Path._create_closed(
  3432. np.column_stack([xs, ys][maybe_swap]))
  3433. patch = mpatches.PathPatch(path, **kwargs)
  3434. self.add_artist(patch)
  3435. return patch
  3436. # input validation
  3437. N = len(bxpstats)
  3438. datashape_message = ("List of boxplot statistics and `{0}` "
  3439. "values must have same the length")
  3440. # check position
  3441. if positions is None:
  3442. positions = list(range(1, N + 1))
  3443. elif len(positions) != N:
  3444. raise ValueError(datashape_message.format("positions"))
  3445. positions = np.array(positions)
  3446. if len(positions) > 0 and not all(isinstance(p, Real) for p in positions):
  3447. raise TypeError("positions should be an iterable of numbers")
  3448. # width
  3449. if widths is None:
  3450. widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N
  3451. elif np.isscalar(widths):
  3452. widths = [widths] * N
  3453. elif len(widths) != N:
  3454. raise ValueError(datashape_message.format("widths"))
  3455. # capwidth
  3456. if capwidths is None:
  3457. capwidths = 0.5 * np.array(widths)
  3458. elif np.isscalar(capwidths):
  3459. capwidths = [capwidths] * N
  3460. elif len(capwidths) != N:
  3461. raise ValueError(datashape_message.format("capwidths"))
  3462. for pos, width, stats, capwidth in zip(positions, widths, bxpstats,
  3463. capwidths):
  3464. # try to find a new label
  3465. datalabels.append(stats.get('label', pos))
  3466. # whisker coords
  3467. whis_x = [pos, pos]
  3468. whislo_y = [stats['q1'], stats['whislo']]
  3469. whishi_y = [stats['q3'], stats['whishi']]
  3470. # cap coords
  3471. cap_left = pos - capwidth * 0.5
  3472. cap_right = pos + capwidth * 0.5
  3473. cap_x = [cap_left, cap_right]
  3474. cap_lo = np.full(2, stats['whislo'])
  3475. cap_hi = np.full(2, stats['whishi'])
  3476. # box and median coords
  3477. box_left = pos - width * 0.5
  3478. box_right = pos + width * 0.5
  3479. med_y = [stats['med'], stats['med']]
  3480. # notched boxes
  3481. if shownotches:
  3482. notch_left = pos - width * 0.25
  3483. notch_right = pos + width * 0.25
  3484. box_x = [box_left, box_right, box_right, notch_right,
  3485. box_right, box_right, box_left, box_left, notch_left,
  3486. box_left, box_left]
  3487. box_y = [stats['q1'], stats['q1'], stats['cilo'],
  3488. stats['med'], stats['cihi'], stats['q3'],
  3489. stats['q3'], stats['cihi'], stats['med'],
  3490. stats['cilo'], stats['q1']]
  3491. med_x = [notch_left, notch_right]
  3492. # plain boxes
  3493. else:
  3494. box_x = [box_left, box_right, box_right, box_left, box_left]
  3495. box_y = [stats['q1'], stats['q1'], stats['q3'], stats['q3'],
  3496. stats['q1']]
  3497. med_x = [box_left, box_right]
  3498. # maybe draw the box
  3499. if showbox:
  3500. do_box = do_patch if patch_artist else do_plot
  3501. boxes.append(do_box(box_x, box_y, **box_kw))
  3502. # draw the whiskers
  3503. whiskers.append(do_plot(whis_x, whislo_y, **whisker_kw))
  3504. whiskers.append(do_plot(whis_x, whishi_y, **whisker_kw))
  3505. # maybe draw the caps
  3506. if showcaps:
  3507. caps.append(do_plot(cap_x, cap_lo, **cap_kw))
  3508. caps.append(do_plot(cap_x, cap_hi, **cap_kw))
  3509. # draw the medians
  3510. medians.append(do_plot(med_x, med_y, **median_kw))
  3511. # maybe draw the means
  3512. if showmeans:
  3513. if meanline:
  3514. means.append(do_plot(
  3515. [box_left, box_right], [stats['mean'], stats['mean']],
  3516. **mean_kw
  3517. ))
  3518. else:
  3519. means.append(do_plot([pos], [stats['mean']], **mean_kw))
  3520. # maybe draw the fliers
  3521. if showfliers:
  3522. flier_x = np.full(len(stats['fliers']), pos, dtype=np.float64)
  3523. flier_y = stats['fliers']
  3524. fliers.append(do_plot(flier_x, flier_y, **flier_kw))
  3525. if manage_ticks:
  3526. axis_name = "x" if vert else "y"
  3527. interval = getattr(self.dataLim, f"interval{axis_name}")
  3528. axis = self._axis_map[axis_name]
  3529. positions = axis.convert_units(positions)
  3530. # The 0.5 additional padding ensures reasonable-looking boxes
  3531. # even when drawing a single box. We set the sticky edge to
  3532. # prevent margins expansion, in order to match old behavior (back
  3533. # when separate calls to boxplot() would completely reset the axis
  3534. # limits regardless of what was drawn before). The sticky edges
  3535. # are attached to the median lines, as they are always present.
  3536. interval[:] = (min(interval[0], min(positions) - .5),
  3537. max(interval[1], max(positions) + .5))
  3538. for median, position in zip(medians, positions):
  3539. getattr(median.sticky_edges, axis_name).extend(
  3540. [position - .5, position + .5])
  3541. # Modified from Axis.set_ticks and Axis.set_ticklabels.
  3542. locator = axis.get_major_locator()
  3543. if not isinstance(axis.get_major_locator(),
  3544. mticker.FixedLocator):
  3545. locator = mticker.FixedLocator([])
  3546. axis.set_major_locator(locator)
  3547. locator.locs = np.array([*locator.locs, *positions])
  3548. formatter = axis.get_major_formatter()
  3549. if not isinstance(axis.get_major_formatter(),
  3550. mticker.FixedFormatter):
  3551. formatter = mticker.FixedFormatter([])
  3552. axis.set_major_formatter(formatter)
  3553. formatter.seq = [*formatter.seq, *datalabels]
  3554. self._request_autoscale_view()
  3555. return dict(whiskers=whiskers, caps=caps, boxes=boxes,
  3556. medians=medians, fliers=fliers, means=means)
  3557. @staticmethod
  3558. def _parse_scatter_color_args(c, edgecolors, kwargs, xsize,
  3559. get_next_color_func):
  3560. """
  3561. Helper function to process color related arguments of `.Axes.scatter`.
  3562. Argument precedence for facecolors:
  3563. - c (if not None)
  3564. - kwargs['facecolor']
  3565. - kwargs['facecolors']
  3566. - kwargs['color'] (==kwcolor)
  3567. - 'b' if in classic mode else the result of ``get_next_color_func()``
  3568. Argument precedence for edgecolors:
  3569. - kwargs['edgecolor']
  3570. - edgecolors (is an explicit kw argument in scatter())
  3571. - kwargs['color'] (==kwcolor)
  3572. - 'face' if not in classic mode else None
  3573. Parameters
  3574. ----------
  3575. c : color or sequence or sequence of color or None
  3576. See argument description of `.Axes.scatter`.
  3577. edgecolors : color or sequence of color or {'face', 'none'} or None
  3578. See argument description of `.Axes.scatter`.
  3579. kwargs : dict
  3580. Additional kwargs. If these keys exist, we pop and process them:
  3581. 'facecolors', 'facecolor', 'edgecolor', 'color'
  3582. Note: The dict is modified by this function.
  3583. xsize : int
  3584. The size of the x and y arrays passed to `.Axes.scatter`.
  3585. get_next_color_func : callable
  3586. A callable that returns a color. This color is used as facecolor
  3587. if no other color is provided.
  3588. Note, that this is a function rather than a fixed color value to
  3589. support conditional evaluation of the next color. As of the
  3590. current implementation obtaining the next color from the
  3591. property cycle advances the cycle. This must only happen if we
  3592. actually use the color, which will only be decided within this
  3593. method.
  3594. Returns
  3595. -------
  3596. c
  3597. The input *c* if it was not *None*, else a color derived from the
  3598. other inputs or defaults.
  3599. colors : array(N, 4) or None
  3600. The facecolors as RGBA values, or *None* if a colormap is used.
  3601. edgecolors
  3602. The edgecolor.
  3603. """
  3604. facecolors = kwargs.pop('facecolors', None)
  3605. facecolors = kwargs.pop('facecolor', facecolors)
  3606. edgecolors = kwargs.pop('edgecolor', edgecolors)
  3607. kwcolor = kwargs.pop('color', None)
  3608. if kwcolor is not None and c is not None:
  3609. raise ValueError("Supply a 'c' argument or a 'color'"
  3610. " kwarg but not both; they differ but"
  3611. " their functionalities overlap.")
  3612. if kwcolor is not None:
  3613. try:
  3614. mcolors.to_rgba_array(kwcolor)
  3615. except ValueError as err:
  3616. raise ValueError(
  3617. "'color' kwarg must be a color or sequence of color "
  3618. "specs. For a sequence of values to be color-mapped, use "
  3619. "the 'c' argument instead.") from err
  3620. if edgecolors is None:
  3621. edgecolors = kwcolor
  3622. if facecolors is None:
  3623. facecolors = kwcolor
  3624. if edgecolors is None and not mpl.rcParams['_internal.classic_mode']:
  3625. edgecolors = mpl.rcParams['scatter.edgecolors']
  3626. c_was_none = c is None
  3627. if c is None:
  3628. c = (facecolors if facecolors is not None
  3629. else "b" if mpl.rcParams['_internal.classic_mode']
  3630. else get_next_color_func())
  3631. c_is_string_or_strings = (
  3632. isinstance(c, str)
  3633. or (np.iterable(c) and len(c) > 0
  3634. and isinstance(cbook._safe_first_finite(c), str)))
  3635. def invalid_shape_exception(csize, xsize):
  3636. return ValueError(
  3637. f"'c' argument has {csize} elements, which is inconsistent "
  3638. f"with 'x' and 'y' with size {xsize}.")
  3639. c_is_mapped = False # Unless proven otherwise below.
  3640. valid_shape = True # Unless proven otherwise below.
  3641. if not c_was_none and kwcolor is None and not c_is_string_or_strings:
  3642. try: # First, does 'c' look suitable for value-mapping?
  3643. c = np.asanyarray(c, dtype=float)
  3644. except ValueError:
  3645. pass # Failed to convert to float array; must be color specs.
  3646. else:
  3647. # handle the documented special case of a 2D array with 1
  3648. # row which as RGB(A) to broadcast.
  3649. if c.shape == (1, 4) or c.shape == (1, 3):
  3650. c_is_mapped = False
  3651. if c.size != xsize:
  3652. valid_shape = False
  3653. # If c can be either mapped values or an RGB(A) color, prefer
  3654. # the former if shapes match, the latter otherwise.
  3655. elif c.size == xsize:
  3656. c = c.ravel()
  3657. c_is_mapped = True
  3658. else: # Wrong size; it must not be intended for mapping.
  3659. if c.shape in ((3,), (4,)):
  3660. _api.warn_external(
  3661. "*c* argument looks like a single numeric RGB or "
  3662. "RGBA sequence, which should be avoided as value-"
  3663. "mapping will have precedence in case its length "
  3664. "matches with *x* & *y*. Please use the *color* "
  3665. "keyword-argument or provide a 2D array "
  3666. "with a single row if you intend to specify "
  3667. "the same RGB or RGBA value for all points.")
  3668. valid_shape = False
  3669. if not c_is_mapped:
  3670. try: # Is 'c' acceptable as PathCollection facecolors?
  3671. colors = mcolors.to_rgba_array(c)
  3672. except (TypeError, ValueError) as err:
  3673. if "RGBA values should be within 0-1 range" in str(err):
  3674. raise
  3675. else:
  3676. if not valid_shape:
  3677. raise invalid_shape_exception(c.size, xsize) from err
  3678. # Both the mapping *and* the RGBA conversion failed: pretty
  3679. # severe failure => one may appreciate a verbose feedback.
  3680. raise ValueError(
  3681. f"'c' argument must be a color, a sequence of colors, "
  3682. f"or a sequence of numbers, not {c!r}") from err
  3683. else:
  3684. if len(colors) not in (0, 1, xsize):
  3685. # NB: remember that a single color is also acceptable.
  3686. # Besides *colors* will be an empty array if c == 'none'.
  3687. raise invalid_shape_exception(len(colors), xsize)
  3688. else:
  3689. colors = None # use cmap, norm after collection is created
  3690. return c, colors, edgecolors
  3691. @_preprocess_data(replace_names=["x", "y", "s", "linewidths",
  3692. "edgecolors", "c", "facecolor",
  3693. "facecolors", "color"],
  3694. label_namer="y")
  3695. @_docstring.interpd
  3696. def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
  3697. vmin=None, vmax=None, alpha=None, linewidths=None, *,
  3698. edgecolors=None, plotnonfinite=False, **kwargs):
  3699. """
  3700. A scatter plot of *y* vs. *x* with varying marker size and/or color.
  3701. Parameters
  3702. ----------
  3703. x, y : float or array-like, shape (n, )
  3704. The data positions.
  3705. s : float or array-like, shape (n, ), optional
  3706. The marker size in points**2 (typographic points are 1/72 in.).
  3707. Default is ``rcParams['lines.markersize'] ** 2``.
  3708. The linewidth and edgecolor can visually interact with the marker
  3709. size, and can lead to artifacts if the marker size is smaller than
  3710. the linewidth.
  3711. If the linewidth is greater than 0 and the edgecolor is anything
  3712. but *'none'*, then the effective size of the marker will be
  3713. increased by half the linewidth because the stroke will be centered
  3714. on the edge of the shape.
  3715. To eliminate the marker edge either set *linewidth=0* or
  3716. *edgecolor='none'*.
  3717. c : array-like or list of colors or color, optional
  3718. The marker colors. Possible values:
  3719. - A scalar or sequence of n numbers to be mapped to colors using
  3720. *cmap* and *norm*.
  3721. - A 2D array in which the rows are RGB or RGBA.
  3722. - A sequence of colors of length n.
  3723. - A single color format string.
  3724. Note that *c* should not be a single numeric RGB or RGBA sequence
  3725. because that is indistinguishable from an array of values to be
  3726. colormapped. If you want to specify the same RGB or RGBA value for
  3727. all points, use a 2D array with a single row. Otherwise,
  3728. value-matching will have precedence in case of a size matching with
  3729. *x* and *y*.
  3730. If you wish to specify a single color for all points
  3731. prefer the *color* keyword argument.
  3732. Defaults to `None`. In that case the marker color is determined
  3733. by the value of *color*, *facecolor* or *facecolors*. In case
  3734. those are not specified or `None`, the marker color is determined
  3735. by the next color of the ``Axes``' current "shape and fill" color
  3736. cycle. This cycle defaults to :rc:`axes.prop_cycle`.
  3737. marker : `~.markers.MarkerStyle`, default: :rc:`scatter.marker`
  3738. The marker style. *marker* can be either an instance of the class
  3739. or the text shorthand for a particular marker.
  3740. See :mod:`matplotlib.markers` for more information about marker
  3741. styles.
  3742. %(cmap_doc)s
  3743. This parameter is ignored if *c* is RGB(A).
  3744. %(norm_doc)s
  3745. This parameter is ignored if *c* is RGB(A).
  3746. %(vmin_vmax_doc)s
  3747. This parameter is ignored if *c* is RGB(A).
  3748. alpha : float, default: None
  3749. The alpha blending value, between 0 (transparent) and 1 (opaque).
  3750. linewidths : float or array-like, default: :rc:`lines.linewidth`
  3751. The linewidth of the marker edges. Note: The default *edgecolors*
  3752. is 'face'. You may want to change this as well.
  3753. edgecolors : {'face', 'none', *None*} or color or sequence of color, \
  3754. default: :rc:`scatter.edgecolors`
  3755. The edge color of the marker. Possible values:
  3756. - 'face': The edge color will always be the same as the face color.
  3757. - 'none': No patch boundary will be drawn.
  3758. - A color or sequence of colors.
  3759. For non-filled markers, *edgecolors* is ignored. Instead, the color
  3760. is determined like with 'face', i.e. from *c*, *colors*, or
  3761. *facecolors*.
  3762. plotnonfinite : bool, default: False
  3763. Whether to plot points with nonfinite *c* (i.e. ``inf``, ``-inf``
  3764. or ``nan``). If ``True`` the points are drawn with the *bad*
  3765. colormap color (see `.Colormap.set_bad`).
  3766. Returns
  3767. -------
  3768. `~matplotlib.collections.PathCollection`
  3769. Other Parameters
  3770. ----------------
  3771. data : indexable object, optional
  3772. DATA_PARAMETER_PLACEHOLDER
  3773. **kwargs : `~matplotlib.collections.Collection` properties
  3774. See Also
  3775. --------
  3776. plot : To plot scatter plots when markers are identical in size and
  3777. color.
  3778. Notes
  3779. -----
  3780. * The `.plot` function will be faster for scatterplots where markers
  3781. don't vary in size or color.
  3782. * Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which
  3783. case all masks will be combined and only unmasked points will be
  3784. plotted.
  3785. * Fundamentally, scatter works with 1D arrays; *x*, *y*, *s*, and *c*
  3786. may be input as N-D arrays, but within scatter they will be
  3787. flattened. The exception is *c*, which will be flattened only if its
  3788. size matches the size of *x* and *y*.
  3789. """
  3790. # add edgecolors and linewidths to kwargs so they
  3791. # can be processed by normailze_kwargs
  3792. if edgecolors is not None:
  3793. kwargs.update({'edgecolors': edgecolors})
  3794. if linewidths is not None:
  3795. kwargs.update({'linewidths': linewidths})
  3796. kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection)
  3797. # re direct linewidth and edgecolor so it can be
  3798. # further processed by the rest of the function
  3799. linewidths = kwargs.pop('linewidth', None)
  3800. edgecolors = kwargs.pop('edgecolor', None)
  3801. # Process **kwargs to handle aliases, conflicts with explicit kwargs:
  3802. x, y = self._process_unit_info([("x", x), ("y", y)], kwargs)
  3803. # np.ma.ravel yields an ndarray, not a masked array,
  3804. # unless its argument is a masked array.
  3805. x = np.ma.ravel(x)
  3806. y = np.ma.ravel(y)
  3807. if x.size != y.size:
  3808. raise ValueError("x and y must be the same size")
  3809. if s is None:
  3810. s = (20 if mpl.rcParams['_internal.classic_mode'] else
  3811. mpl.rcParams['lines.markersize'] ** 2.0)
  3812. s = np.ma.ravel(s)
  3813. if (len(s) not in (1, x.size) or
  3814. (not np.issubdtype(s.dtype, np.floating) and
  3815. not np.issubdtype(s.dtype, np.integer))):
  3816. raise ValueError(
  3817. "s must be a scalar, "
  3818. "or float array-like with the same size as x and y")
  3819. # get the original edgecolor the user passed before we normalize
  3820. orig_edgecolor = edgecolors
  3821. if edgecolors is None:
  3822. orig_edgecolor = kwargs.get('edgecolor', None)
  3823. c, colors, edgecolors = \
  3824. self._parse_scatter_color_args(
  3825. c, edgecolors, kwargs, x.size,
  3826. get_next_color_func=self._get_patches_for_fill.get_next_color)
  3827. if plotnonfinite and colors is None:
  3828. c = np.ma.masked_invalid(c)
  3829. x, y, s, edgecolors, linewidths = \
  3830. cbook._combine_masks(x, y, s, edgecolors, linewidths)
  3831. else:
  3832. x, y, s, c, colors, edgecolors, linewidths = \
  3833. cbook._combine_masks(
  3834. x, y, s, c, colors, edgecolors, linewidths)
  3835. # Unmask edgecolors if it was actually a single RGB or RGBA.
  3836. if (x.size in (3, 4)
  3837. and np.ma.is_masked(edgecolors)
  3838. and not np.ma.is_masked(orig_edgecolor)):
  3839. edgecolors = edgecolors.data
  3840. scales = s # Renamed for readability below.
  3841. # load default marker from rcParams
  3842. if marker is None:
  3843. marker = mpl.rcParams['scatter.marker']
  3844. if isinstance(marker, mmarkers.MarkerStyle):
  3845. marker_obj = marker
  3846. else:
  3847. marker_obj = mmarkers.MarkerStyle(marker)
  3848. path = marker_obj.get_path().transformed(
  3849. marker_obj.get_transform())
  3850. if not marker_obj.is_filled():
  3851. if orig_edgecolor is not None:
  3852. _api.warn_external(
  3853. f"You passed a edgecolor/edgecolors ({orig_edgecolor!r}) "
  3854. f"for an unfilled marker ({marker!r}). Matplotlib is "
  3855. "ignoring the edgecolor in favor of the facecolor. This "
  3856. "behavior may change in the future."
  3857. )
  3858. # We need to handle markers that cannot be filled (like
  3859. # '+' and 'x') differently than markers that can be
  3860. # filled, but have their fillstyle set to 'none'. This is
  3861. # to get:
  3862. #
  3863. # - respecting the fillestyle if set
  3864. # - maintaining back-compatibility for querying the facecolor of
  3865. # the un-fillable markers.
  3866. #
  3867. # While not an ideal situation, but is better than the
  3868. # alternatives.
  3869. if marker_obj.get_fillstyle() == 'none':
  3870. # promote the facecolor to be the edgecolor
  3871. edgecolors = colors
  3872. # set the facecolor to 'none' (at the last chance) because
  3873. # we cannot fill a path if the facecolor is non-null
  3874. # (which is defendable at the renderer level).
  3875. colors = 'none'
  3876. else:
  3877. # if we are not nulling the face color we can do this
  3878. # simpler
  3879. edgecolors = 'face'
  3880. if linewidths is None:
  3881. linewidths = mpl.rcParams['lines.linewidth']
  3882. elif np.iterable(linewidths):
  3883. linewidths = [
  3884. lw if lw is not None else mpl.rcParams['lines.linewidth']
  3885. for lw in linewidths]
  3886. offsets = np.ma.column_stack([x, y])
  3887. collection = mcoll.PathCollection(
  3888. (path,), scales,
  3889. facecolors=colors,
  3890. edgecolors=edgecolors,
  3891. linewidths=linewidths,
  3892. offsets=offsets,
  3893. offset_transform=kwargs.pop('transform', self.transData),
  3894. alpha=alpha,
  3895. )
  3896. collection.set_transform(mtransforms.IdentityTransform())
  3897. if colors is None:
  3898. collection.set_array(c)
  3899. collection.set_cmap(cmap)
  3900. collection.set_norm(norm)
  3901. collection._scale_norm(norm, vmin, vmax)
  3902. else:
  3903. extra_kwargs = {
  3904. 'cmap': cmap, 'norm': norm, 'vmin': vmin, 'vmax': vmax
  3905. }
  3906. extra_keys = [k for k, v in extra_kwargs.items() if v is not None]
  3907. if any(extra_keys):
  3908. keys_str = ", ".join(f"'{k}'" for k in extra_keys)
  3909. _api.warn_external(
  3910. "No data for colormapping provided via 'c'. "
  3911. f"Parameters {keys_str} will be ignored")
  3912. collection._internal_update(kwargs)
  3913. # Classic mode only:
  3914. # ensure there are margins to allow for the
  3915. # finite size of the symbols. In v2.x, margins
  3916. # are present by default, so we disable this
  3917. # scatter-specific override.
  3918. if mpl.rcParams['_internal.classic_mode']:
  3919. if self._xmargin < 0.05 and x.size > 0:
  3920. self.set_xmargin(0.05)
  3921. if self._ymargin < 0.05 and x.size > 0:
  3922. self.set_ymargin(0.05)
  3923. self.add_collection(collection)
  3924. self._request_autoscale_view()
  3925. return collection
  3926. @_preprocess_data(replace_names=["x", "y", "C"], label_namer="y")
  3927. @_docstring.dedent_interpd
  3928. def hexbin(self, x, y, C=None, gridsize=100, bins=None,
  3929. xscale='linear', yscale='linear', extent=None,
  3930. cmap=None, norm=None, vmin=None, vmax=None,
  3931. alpha=None, linewidths=None, edgecolors='face',
  3932. reduce_C_function=np.mean, mincnt=None, marginals=False,
  3933. **kwargs):
  3934. """
  3935. Make a 2D hexagonal binning plot of points *x*, *y*.
  3936. If *C* is *None*, the value of the hexagon is determined by the number
  3937. of points in the hexagon. Otherwise, *C* specifies values at the
  3938. coordinate (x[i], y[i]). For each hexagon, these values are reduced
  3939. using *reduce_C_function*.
  3940. Parameters
  3941. ----------
  3942. x, y : array-like
  3943. The data positions. *x* and *y* must be of the same length.
  3944. C : array-like, optional
  3945. If given, these values are accumulated in the bins. Otherwise,
  3946. every point has a value of 1. Must be of the same length as *x*
  3947. and *y*.
  3948. gridsize : int or (int, int), default: 100
  3949. If a single int, the number of hexagons in the *x*-direction.
  3950. The number of hexagons in the *y*-direction is chosen such that
  3951. the hexagons are approximately regular.
  3952. Alternatively, if a tuple (*nx*, *ny*), the number of hexagons
  3953. in the *x*-direction and the *y*-direction. In the
  3954. *y*-direction, counting is done along vertically aligned
  3955. hexagons, not along the zig-zag chains of hexagons; see the
  3956. following illustration.
  3957. .. plot::
  3958. import numpy
  3959. import matplotlib.pyplot as plt
  3960. np.random.seed(19680801)
  3961. n= 300
  3962. x = np.random.standard_normal(n)
  3963. y = np.random.standard_normal(n)
  3964. fig, ax = plt.subplots(figsize=(4, 4))
  3965. h = ax.hexbin(x, y, gridsize=(5, 3))
  3966. hx, hy = h.get_offsets().T
  3967. ax.plot(hx[24::3], hy[24::3], 'ro-')
  3968. ax.plot(hx[-3:], hy[-3:], 'ro-')
  3969. ax.set_title('gridsize=(5, 3)')
  3970. ax.axis('off')
  3971. To get approximately regular hexagons, choose
  3972. :math:`n_x = \\sqrt{3}\\,n_y`.
  3973. bins : 'log' or int or sequence, default: None
  3974. Discretization of the hexagon values.
  3975. - If *None*, no binning is applied; the color of each hexagon
  3976. directly corresponds to its count value.
  3977. - If 'log', use a logarithmic scale for the colormap.
  3978. Internally, :math:`log_{10}(i+1)` is used to determine the
  3979. hexagon color. This is equivalent to ``norm=LogNorm()``.
  3980. - If an integer, divide the counts in the specified number
  3981. of bins, and color the hexagons accordingly.
  3982. - If a sequence of values, the values of the lower bound of
  3983. the bins to be used.
  3984. xscale : {'linear', 'log'}, default: 'linear'
  3985. Use a linear or log10 scale on the horizontal axis.
  3986. yscale : {'linear', 'log'}, default: 'linear'
  3987. Use a linear or log10 scale on the vertical axis.
  3988. mincnt : int >= 0, default: *None*
  3989. If not *None*, only display cells with at least *mincnt*
  3990. number of points in the cell.
  3991. marginals : bool, default: *False*
  3992. If marginals is *True*, plot the marginal density as
  3993. colormapped rectangles along the bottom of the x-axis and
  3994. left of the y-axis.
  3995. extent : 4-tuple of float, default: *None*
  3996. The limits of the bins (xmin, xmax, ymin, ymax).
  3997. The default assigns the limits based on
  3998. *gridsize*, *x*, *y*, *xscale* and *yscale*.
  3999. If *xscale* or *yscale* is set to 'log', the limits are
  4000. expected to be the exponent for a power of 10. E.g. for
  4001. x-limits of 1 and 50 in 'linear' scale and y-limits
  4002. of 10 and 1000 in 'log' scale, enter (1, 50, 1, 3).
  4003. Returns
  4004. -------
  4005. `~matplotlib.collections.PolyCollection`
  4006. A `.PolyCollection` defining the hexagonal bins.
  4007. - `.PolyCollection.get_offsets` contains a Mx2 array containing
  4008. the x, y positions of the M hexagon centers.
  4009. - `.PolyCollection.get_array` contains the values of the M
  4010. hexagons.
  4011. If *marginals* is *True*, horizontal
  4012. bar and vertical bar (both PolyCollections) will be attached
  4013. to the return collection as attributes *hbar* and *vbar*.
  4014. Other Parameters
  4015. ----------------
  4016. %(cmap_doc)s
  4017. %(norm_doc)s
  4018. %(vmin_vmax_doc)s
  4019. alpha : float between 0 and 1, optional
  4020. The alpha blending value, between 0 (transparent) and 1 (opaque).
  4021. linewidths : float, default: *None*
  4022. If *None*, defaults to :rc:`patch.linewidth`.
  4023. edgecolors : {'face', 'none', *None*} or color, default: 'face'
  4024. The color of the hexagon edges. Possible values are:
  4025. - 'face': Draw the edges in the same color as the fill color.
  4026. - 'none': No edges are drawn. This can sometimes lead to unsightly
  4027. unpainted pixels between the hexagons.
  4028. - *None*: Draw outlines in the default color.
  4029. - An explicit color.
  4030. reduce_C_function : callable, default: `numpy.mean`
  4031. The function to aggregate *C* within the bins. It is ignored if
  4032. *C* is not given. This must have the signature::
  4033. def reduce_C_function(C: array) -> float
  4034. Commonly used functions are:
  4035. - `numpy.mean`: average of the points
  4036. - `numpy.sum`: integral of the point values
  4037. - `numpy.amax`: value taken from the largest point
  4038. By default will only reduce cells with at least 1 point because some
  4039. reduction functions (such as `numpy.amax`) will error/warn with empty
  4040. input. Changing *mincnt* will adjust the cutoff, and if set to 0 will
  4041. pass empty input to the reduction function.
  4042. data : indexable object, optional
  4043. DATA_PARAMETER_PLACEHOLDER
  4044. **kwargs : `~matplotlib.collections.PolyCollection` properties
  4045. All other keyword arguments are passed on to `.PolyCollection`:
  4046. %(PolyCollection:kwdoc)s
  4047. See Also
  4048. --------
  4049. hist2d : 2D histogram rectangular bins
  4050. """
  4051. self._process_unit_info([("x", x), ("y", y)], kwargs, convert=False)
  4052. x, y, C = cbook.delete_masked_points(x, y, C)
  4053. # Set the size of the hexagon grid
  4054. if np.iterable(gridsize):
  4055. nx, ny = gridsize
  4056. else:
  4057. nx = gridsize
  4058. ny = int(nx / math.sqrt(3))
  4059. # Count the number of data in each hexagon
  4060. x = np.asarray(x, float)
  4061. y = np.asarray(y, float)
  4062. # Will be log()'d if necessary, and then rescaled.
  4063. tx = x
  4064. ty = y
  4065. if xscale == 'log':
  4066. if np.any(x <= 0.0):
  4067. raise ValueError(
  4068. "x contains non-positive values, so cannot be log-scaled")
  4069. tx = np.log10(tx)
  4070. if yscale == 'log':
  4071. if np.any(y <= 0.0):
  4072. raise ValueError(
  4073. "y contains non-positive values, so cannot be log-scaled")
  4074. ty = np.log10(ty)
  4075. if extent is not None:
  4076. xmin, xmax, ymin, ymax = extent
  4077. else:
  4078. xmin, xmax = (tx.min(), tx.max()) if len(x) else (0, 1)
  4079. ymin, ymax = (ty.min(), ty.max()) if len(y) else (0, 1)
  4080. # to avoid issues with singular data, expand the min/max pairs
  4081. xmin, xmax = mtransforms.nonsingular(xmin, xmax, expander=0.1)
  4082. ymin, ymax = mtransforms.nonsingular(ymin, ymax, expander=0.1)
  4083. nx1 = nx + 1
  4084. ny1 = ny + 1
  4085. nx2 = nx
  4086. ny2 = ny
  4087. n = nx1 * ny1 + nx2 * ny2
  4088. # In the x-direction, the hexagons exactly cover the region from
  4089. # xmin to xmax. Need some padding to avoid roundoff errors.
  4090. padding = 1.e-9 * (xmax - xmin)
  4091. xmin -= padding
  4092. xmax += padding
  4093. sx = (xmax - xmin) / nx
  4094. sy = (ymax - ymin) / ny
  4095. # Positions in hexagon index coordinates.
  4096. ix = (tx - xmin) / sx
  4097. iy = (ty - ymin) / sy
  4098. ix1 = np.round(ix).astype(int)
  4099. iy1 = np.round(iy).astype(int)
  4100. ix2 = np.floor(ix).astype(int)
  4101. iy2 = np.floor(iy).astype(int)
  4102. # flat indices, plus one so that out-of-range points go to position 0.
  4103. i1 = np.where((0 <= ix1) & (ix1 < nx1) & (0 <= iy1) & (iy1 < ny1),
  4104. ix1 * ny1 + iy1 + 1, 0)
  4105. i2 = np.where((0 <= ix2) & (ix2 < nx2) & (0 <= iy2) & (iy2 < ny2),
  4106. ix2 * ny2 + iy2 + 1, 0)
  4107. d1 = (ix - ix1) ** 2 + 3.0 * (iy - iy1) ** 2
  4108. d2 = (ix - ix2 - 0.5) ** 2 + 3.0 * (iy - iy2 - 0.5) ** 2
  4109. bdist = (d1 < d2)
  4110. if C is None: # [1:] drops out-of-range points.
  4111. counts1 = np.bincount(i1[bdist], minlength=1 + nx1 * ny1)[1:]
  4112. counts2 = np.bincount(i2[~bdist], minlength=1 + nx2 * ny2)[1:]
  4113. accum = np.concatenate([counts1, counts2]).astype(float)
  4114. if mincnt is not None:
  4115. accum[accum < mincnt] = np.nan
  4116. C = np.ones(len(x))
  4117. else:
  4118. # store the C values in a list per hexagon index
  4119. Cs_at_i1 = [[] for _ in range(1 + nx1 * ny1)]
  4120. Cs_at_i2 = [[] for _ in range(1 + nx2 * ny2)]
  4121. for i in range(len(x)):
  4122. if bdist[i]:
  4123. Cs_at_i1[i1[i]].append(C[i])
  4124. else:
  4125. Cs_at_i2[i2[i]].append(C[i])
  4126. if mincnt is None:
  4127. mincnt = 1
  4128. accum = np.array(
  4129. [reduce_C_function(acc) if len(acc) >= mincnt else np.nan
  4130. for Cs_at_i in [Cs_at_i1, Cs_at_i2]
  4131. for acc in Cs_at_i[1:]], # [1:] drops out-of-range points.
  4132. float)
  4133. good_idxs = ~np.isnan(accum)
  4134. offsets = np.zeros((n, 2), float)
  4135. offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1)
  4136. offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1)
  4137. offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2)
  4138. offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5
  4139. offsets[:, 0] *= sx
  4140. offsets[:, 1] *= sy
  4141. offsets[:, 0] += xmin
  4142. offsets[:, 1] += ymin
  4143. # remove accumulation bins with no data
  4144. offsets = offsets[good_idxs, :]
  4145. accum = accum[good_idxs]
  4146. polygon = [sx, sy / 3] * np.array(
  4147. [[.5, -.5], [.5, .5], [0., 1.], [-.5, .5], [-.5, -.5], [0., -1.]])
  4148. if linewidths is None:
  4149. linewidths = [mpl.rcParams['patch.linewidth']]
  4150. if xscale == 'log' or yscale == 'log':
  4151. polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1)
  4152. if xscale == 'log':
  4153. polygons[:, :, 0] = 10.0 ** polygons[:, :, 0]
  4154. xmin = 10.0 ** xmin
  4155. xmax = 10.0 ** xmax
  4156. self.set_xscale(xscale)
  4157. if yscale == 'log':
  4158. polygons[:, :, 1] = 10.0 ** polygons[:, :, 1]
  4159. ymin = 10.0 ** ymin
  4160. ymax = 10.0 ** ymax
  4161. self.set_yscale(yscale)
  4162. collection = mcoll.PolyCollection(
  4163. polygons,
  4164. edgecolors=edgecolors,
  4165. linewidths=linewidths,
  4166. )
  4167. else:
  4168. collection = mcoll.PolyCollection(
  4169. [polygon],
  4170. edgecolors=edgecolors,
  4171. linewidths=linewidths,
  4172. offsets=offsets,
  4173. offset_transform=mtransforms.AffineDeltaTransform(
  4174. self.transData),
  4175. )
  4176. # Set normalizer if bins is 'log'
  4177. if bins == 'log':
  4178. if norm is not None:
  4179. _api.warn_external("Only one of 'bins' and 'norm' arguments "
  4180. f"can be supplied, ignoring bins={bins}")
  4181. else:
  4182. norm = mcolors.LogNorm(vmin=vmin, vmax=vmax)
  4183. vmin = vmax = None
  4184. bins = None
  4185. # autoscale the norm with current accum values if it hasn't been set
  4186. if norm is not None:
  4187. if norm.vmin is None and norm.vmax is None:
  4188. norm.autoscale(accum)
  4189. if bins is not None:
  4190. if not np.iterable(bins):
  4191. minimum, maximum = min(accum), max(accum)
  4192. bins -= 1 # one less edge than bins
  4193. bins = minimum + (maximum - minimum) * np.arange(bins) / bins
  4194. bins = np.sort(bins)
  4195. accum = bins.searchsorted(accum)
  4196. collection.set_array(accum)
  4197. collection.set_cmap(cmap)
  4198. collection.set_norm(norm)
  4199. collection.set_alpha(alpha)
  4200. collection._internal_update(kwargs)
  4201. collection._scale_norm(norm, vmin, vmax)
  4202. corners = ((xmin, ymin), (xmax, ymax))
  4203. self.update_datalim(corners)
  4204. self._request_autoscale_view(tight=True)
  4205. # add the collection last
  4206. self.add_collection(collection, autolim=False)
  4207. if not marginals:
  4208. return collection
  4209. # Process marginals
  4210. bars = []
  4211. for zname, z, zmin, zmax, zscale, nbins in [
  4212. ("x", x, xmin, xmax, xscale, nx),
  4213. ("y", y, ymin, ymax, yscale, 2 * ny),
  4214. ]:
  4215. if zscale == "log":
  4216. bin_edges = np.geomspace(zmin, zmax, nbins + 1)
  4217. else:
  4218. bin_edges = np.linspace(zmin, zmax, nbins + 1)
  4219. verts = np.empty((nbins, 4, 2))
  4220. verts[:, 0, 0] = verts[:, 1, 0] = bin_edges[:-1]
  4221. verts[:, 2, 0] = verts[:, 3, 0] = bin_edges[1:]
  4222. verts[:, 0, 1] = verts[:, 3, 1] = .00
  4223. verts[:, 1, 1] = verts[:, 2, 1] = .05
  4224. if zname == "y":
  4225. verts = verts[:, :, ::-1] # Swap x and y.
  4226. # Sort z-values into bins defined by bin_edges.
  4227. bin_idxs = np.searchsorted(bin_edges, z) - 1
  4228. values = np.empty(nbins)
  4229. for i in range(nbins):
  4230. # Get C-values for each bin, and compute bin value with
  4231. # reduce_C_function.
  4232. ci = C[bin_idxs == i]
  4233. values[i] = reduce_C_function(ci) if len(ci) > 0 else np.nan
  4234. mask = ~np.isnan(values)
  4235. verts = verts[mask]
  4236. values = values[mask]
  4237. trans = getattr(self, f"get_{zname}axis_transform")(which="grid")
  4238. bar = mcoll.PolyCollection(
  4239. verts, transform=trans, edgecolors="face")
  4240. bar.set_array(values)
  4241. bar.set_cmap(cmap)
  4242. bar.set_norm(norm)
  4243. bar.set_alpha(alpha)
  4244. bar._internal_update(kwargs)
  4245. bars.append(self.add_collection(bar, autolim=False))
  4246. collection.hbar, collection.vbar = bars
  4247. def on_changed(collection):
  4248. collection.hbar.set_cmap(collection.get_cmap())
  4249. collection.hbar.set_cmap(collection.get_cmap())
  4250. collection.vbar.set_clim(collection.get_clim())
  4251. collection.vbar.set_clim(collection.get_clim())
  4252. collection.callbacks.connect('changed', on_changed)
  4253. return collection
  4254. @_docstring.dedent_interpd
  4255. def arrow(self, x, y, dx, dy, **kwargs):
  4256. """
  4257. Add an arrow to the Axes.
  4258. This draws an arrow from ``(x, y)`` to ``(x+dx, y+dy)``.
  4259. Parameters
  4260. ----------
  4261. %(FancyArrow)s
  4262. Returns
  4263. -------
  4264. `.FancyArrow`
  4265. The created `.FancyArrow` object.
  4266. Notes
  4267. -----
  4268. The resulting arrow is affected by the Axes aspect ratio and limits.
  4269. This may produce an arrow whose head is not square with its stem. To
  4270. create an arrow whose head is square with its stem,
  4271. use :meth:`annotate` for example:
  4272. >>> ax.annotate("", xy=(0.5, 0.5), xytext=(0, 0),
  4273. ... arrowprops=dict(arrowstyle="->"))
  4274. """
  4275. # Strip away units for the underlying patch since units
  4276. # do not make sense to most patch-like code
  4277. x = self.convert_xunits(x)
  4278. y = self.convert_yunits(y)
  4279. dx = self.convert_xunits(dx)
  4280. dy = self.convert_yunits(dy)
  4281. a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)
  4282. self.add_patch(a)
  4283. self._request_autoscale_view()
  4284. return a
  4285. @_docstring.copy(mquiver.QuiverKey.__init__)
  4286. def quiverkey(self, Q, X, Y, U, label, **kwargs):
  4287. qk = mquiver.QuiverKey(Q, X, Y, U, label, **kwargs)
  4288. self.add_artist(qk)
  4289. return qk
  4290. # Handle units for x and y, if they've been passed
  4291. def _quiver_units(self, args, kwargs):
  4292. if len(args) > 3:
  4293. x, y = args[0:2]
  4294. x, y = self._process_unit_info([("x", x), ("y", y)], kwargs)
  4295. return (x, y) + args[2:]
  4296. return args
  4297. # args can be a combination of X, Y, U, V, C and all should be replaced
  4298. @_preprocess_data()
  4299. @_docstring.dedent_interpd
  4300. def quiver(self, *args, **kwargs):
  4301. """%(quiver_doc)s"""
  4302. # Make sure units are handled for x and y values
  4303. args = self._quiver_units(args, kwargs)
  4304. q = mquiver.Quiver(self, *args, **kwargs)
  4305. self.add_collection(q, autolim=True)
  4306. self._request_autoscale_view()
  4307. return q
  4308. # args can be some combination of X, Y, U, V, C and all should be replaced
  4309. @_preprocess_data()
  4310. @_docstring.dedent_interpd
  4311. def barbs(self, *args, **kwargs):
  4312. """%(barbs_doc)s"""
  4313. # Make sure units are handled for x and y values
  4314. args = self._quiver_units(args, kwargs)
  4315. b = mquiver.Barbs(self, *args, **kwargs)
  4316. self.add_collection(b, autolim=True)
  4317. self._request_autoscale_view()
  4318. return b
  4319. # Uses a custom implementation of data-kwarg handling in
  4320. # _process_plot_var_args.
  4321. def fill(self, *args, data=None, **kwargs):
  4322. """
  4323. Plot filled polygons.
  4324. Parameters
  4325. ----------
  4326. *args : sequence of x, y, [color]
  4327. Each polygon is defined by the lists of *x* and *y* positions of
  4328. its nodes, optionally followed by a *color* specifier. See
  4329. :mod:`matplotlib.colors` for supported color specifiers. The
  4330. standard color cycle is used for polygons without a color
  4331. specifier.
  4332. You can plot multiple polygons by providing multiple *x*, *y*,
  4333. *[color]* groups.
  4334. For example, each of the following is legal::
  4335. ax.fill(x, y) # a polygon with default color
  4336. ax.fill(x, y, "b") # a blue polygon
  4337. ax.fill(x, y, x2, y2) # two polygons
  4338. ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon
  4339. data : indexable object, optional
  4340. An object with labelled data. If given, provide the label names to
  4341. plot in *x* and *y*, e.g.::
  4342. ax.fill("time", "signal",
  4343. data={"time": [0, 1, 2], "signal": [0, 1, 0]})
  4344. Returns
  4345. -------
  4346. list of `~matplotlib.patches.Polygon`
  4347. Other Parameters
  4348. ----------------
  4349. **kwargs : `~matplotlib.patches.Polygon` properties
  4350. Notes
  4351. -----
  4352. Use :meth:`fill_between` if you would like to fill the region between
  4353. two curves.
  4354. """
  4355. # For compatibility(!), get aliases from Line2D rather than Patch.
  4356. kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
  4357. # _get_patches_for_fill returns a generator, convert it to a list.
  4358. patches = [*self._get_patches_for_fill(self, *args, data=data, **kwargs)]
  4359. for poly in patches:
  4360. self.add_patch(poly)
  4361. self._request_autoscale_view()
  4362. return patches
  4363. def _fill_between_x_or_y(
  4364. self, ind_dir, ind, dep1, dep2=0, *,
  4365. where=None, interpolate=False, step=None, **kwargs):
  4366. # Common implementation between fill_between (*ind_dir*="x") and
  4367. # fill_betweenx (*ind_dir*="y"). *ind* is the independent variable,
  4368. # *dep* the dependent variable. The docstring below is interpolated
  4369. # to generate both methods' docstrings.
  4370. """
  4371. Fill the area between two {dir} curves.
  4372. The curves are defined by the points (*{ind}*, *{dep}1*) and (*{ind}*,
  4373. *{dep}2*). This creates one or multiple polygons describing the filled
  4374. area.
  4375. You may exclude some {dir} sections from filling using *where*.
  4376. By default, the edges connect the given points directly. Use *step*
  4377. if the filling should be a step function, i.e. constant in between
  4378. *{ind}*.
  4379. Parameters
  4380. ----------
  4381. {ind} : array (length N)
  4382. The {ind} coordinates of the nodes defining the curves.
  4383. {dep}1 : array (length N) or scalar
  4384. The {dep} coordinates of the nodes defining the first curve.
  4385. {dep}2 : array (length N) or scalar, default: 0
  4386. The {dep} coordinates of the nodes defining the second curve.
  4387. where : array of bool (length N), optional
  4388. Define *where* to exclude some {dir} regions from being filled.
  4389. The filled regions are defined by the coordinates ``{ind}[where]``.
  4390. More precisely, fill between ``{ind}[i]`` and ``{ind}[i+1]`` if
  4391. ``where[i] and where[i+1]``. Note that this definition implies
  4392. that an isolated *True* value between two *False* values in *where*
  4393. will not result in filling. Both sides of the *True* position
  4394. remain unfilled due to the adjacent *False* values.
  4395. interpolate : bool, default: False
  4396. This option is only relevant if *where* is used and the two curves
  4397. are crossing each other.
  4398. Semantically, *where* is often used for *{dep}1* > *{dep}2* or
  4399. similar. By default, the nodes of the polygon defining the filled
  4400. region will only be placed at the positions in the *{ind}* array.
  4401. Such a polygon cannot describe the above semantics close to the
  4402. intersection. The {ind}-sections containing the intersection are
  4403. simply clipped.
  4404. Setting *interpolate* to *True* will calculate the actual
  4405. intersection point and extend the filled region up to this point.
  4406. step : {{'pre', 'post', 'mid'}}, optional
  4407. Define *step* if the filling should be a step function,
  4408. i.e. constant in between *{ind}*. The value determines where the
  4409. step will occur:
  4410. - 'pre': The y value is continued constantly to the left from
  4411. every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the
  4412. value ``y[i]``.
  4413. - 'post': The y value is continued constantly to the right from
  4414. every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the
  4415. value ``y[i]``.
  4416. - 'mid': Steps occur half-way between the *x* positions.
  4417. Returns
  4418. -------
  4419. `.PolyCollection`
  4420. A `.PolyCollection` containing the plotted polygons.
  4421. Other Parameters
  4422. ----------------
  4423. data : indexable object, optional
  4424. DATA_PARAMETER_PLACEHOLDER
  4425. **kwargs
  4426. All other keyword arguments are passed on to `.PolyCollection`.
  4427. They control the `.Polygon` properties:
  4428. %(PolyCollection:kwdoc)s
  4429. See Also
  4430. --------
  4431. fill_between : Fill between two sets of y-values.
  4432. fill_betweenx : Fill between two sets of x-values.
  4433. """
  4434. dep_dir = {"x": "y", "y": "x"}[ind_dir]
  4435. if not mpl.rcParams["_internal.classic_mode"]:
  4436. kwargs = cbook.normalize_kwargs(kwargs, mcoll.Collection)
  4437. if not any(c in kwargs for c in ("color", "facecolor")):
  4438. kwargs["facecolor"] = \
  4439. self._get_patches_for_fill.get_next_color()
  4440. # Handle united data, such as dates
  4441. ind, dep1, dep2 = map(
  4442. ma.masked_invalid, self._process_unit_info(
  4443. [(ind_dir, ind), (dep_dir, dep1), (dep_dir, dep2)], kwargs))
  4444. for name, array in [
  4445. (ind_dir, ind), (f"{dep_dir}1", dep1), (f"{dep_dir}2", dep2)]:
  4446. if array.ndim > 1:
  4447. raise ValueError(f"{name!r} is not 1-dimensional")
  4448. if where is None:
  4449. where = True
  4450. else:
  4451. where = np.asarray(where, dtype=bool)
  4452. if where.size != ind.size:
  4453. raise ValueError(f"where size ({where.size}) does not match "
  4454. f"{ind_dir} size ({ind.size})")
  4455. where = where & ~functools.reduce(
  4456. np.logical_or, map(np.ma.getmaskarray, [ind, dep1, dep2]))
  4457. ind, dep1, dep2 = np.broadcast_arrays(
  4458. np.atleast_1d(ind), dep1, dep2, subok=True)
  4459. polys = []
  4460. for idx0, idx1 in cbook.contiguous_regions(where):
  4461. indslice = ind[idx0:idx1]
  4462. dep1slice = dep1[idx0:idx1]
  4463. dep2slice = dep2[idx0:idx1]
  4464. if step is not None:
  4465. step_func = cbook.STEP_LOOKUP_MAP["steps-" + step]
  4466. indslice, dep1slice, dep2slice = \
  4467. step_func(indslice, dep1slice, dep2slice)
  4468. if not len(indslice):
  4469. continue
  4470. N = len(indslice)
  4471. pts = np.zeros((2 * N + 2, 2))
  4472. if interpolate:
  4473. def get_interp_point(idx):
  4474. im1 = max(idx - 1, 0)
  4475. ind_values = ind[im1:idx+1]
  4476. diff_values = dep1[im1:idx+1] - dep2[im1:idx+1]
  4477. dep1_values = dep1[im1:idx+1]
  4478. if len(diff_values) == 2:
  4479. if np.ma.is_masked(diff_values[1]):
  4480. return ind[im1], dep1[im1]
  4481. elif np.ma.is_masked(diff_values[0]):
  4482. return ind[idx], dep1[idx]
  4483. diff_order = diff_values.argsort()
  4484. diff_root_ind = np.interp(
  4485. 0, diff_values[diff_order], ind_values[diff_order])
  4486. ind_order = ind_values.argsort()
  4487. diff_root_dep = np.interp(
  4488. diff_root_ind,
  4489. ind_values[ind_order], dep1_values[ind_order])
  4490. return diff_root_ind, diff_root_dep
  4491. start = get_interp_point(idx0)
  4492. end = get_interp_point(idx1)
  4493. else:
  4494. # Handle scalar dep2 (e.g. 0): the fill should go all
  4495. # the way down to 0 even if none of the dep1 sample points do.
  4496. start = indslice[0], dep2slice[0]
  4497. end = indslice[-1], dep2slice[-1]
  4498. pts[0] = start
  4499. pts[N + 1] = end
  4500. pts[1:N+1, 0] = indslice
  4501. pts[1:N+1, 1] = dep1slice
  4502. pts[N+2:, 0] = indslice[::-1]
  4503. pts[N+2:, 1] = dep2slice[::-1]
  4504. if ind_dir == "y":
  4505. pts = pts[:, ::-1]
  4506. polys.append(pts)
  4507. collection = mcoll.PolyCollection(polys, **kwargs)
  4508. # now update the datalim and autoscale
  4509. pts = np.vstack([np.hstack([ind[where, None], dep1[where, None]]),
  4510. np.hstack([ind[where, None], dep2[where, None]])])
  4511. if ind_dir == "y":
  4512. pts = pts[:, ::-1]
  4513. up_x = up_y = True
  4514. if "transform" in kwargs:
  4515. up_x, up_y = kwargs["transform"].contains_branch_seperately(self.transData)
  4516. self.update_datalim(pts, updatex=up_x, updatey=up_y)
  4517. self.add_collection(collection, autolim=False)
  4518. self._request_autoscale_view()
  4519. return collection
  4520. def fill_between(self, x, y1, y2=0, where=None, interpolate=False,
  4521. step=None, **kwargs):
  4522. return self._fill_between_x_or_y(
  4523. "x", x, y1, y2,
  4524. where=where, interpolate=interpolate, step=step, **kwargs)
  4525. if _fill_between_x_or_y.__doc__:
  4526. fill_between.__doc__ = _fill_between_x_or_y.__doc__.format(
  4527. dir="horizontal", ind="x", dep="y"
  4528. )
  4529. fill_between = _preprocess_data(
  4530. _docstring.dedent_interpd(fill_between),
  4531. replace_names=["x", "y1", "y2", "where"])
  4532. def fill_betweenx(self, y, x1, x2=0, where=None,
  4533. step=None, interpolate=False, **kwargs):
  4534. return self._fill_between_x_or_y(
  4535. "y", y, x1, x2,
  4536. where=where, interpolate=interpolate, step=step, **kwargs)
  4537. if _fill_between_x_or_y.__doc__:
  4538. fill_betweenx.__doc__ = _fill_between_x_or_y.__doc__.format(
  4539. dir="vertical", ind="y", dep="x"
  4540. )
  4541. fill_betweenx = _preprocess_data(
  4542. _docstring.dedent_interpd(fill_betweenx),
  4543. replace_names=["y", "x1", "x2", "where"])
  4544. #### plotting z(x, y): imshow, pcolor and relatives, contour
  4545. @_preprocess_data()
  4546. @_docstring.interpd
  4547. def imshow(self, X, cmap=None, norm=None, *, aspect=None,
  4548. interpolation=None, alpha=None,
  4549. vmin=None, vmax=None, origin=None, extent=None,
  4550. interpolation_stage=None, filternorm=True, filterrad=4.0,
  4551. resample=None, url=None, **kwargs):
  4552. """
  4553. Display data as an image, i.e., on a 2D regular raster.
  4554. The input may either be actual RGB(A) data, or 2D scalar data, which
  4555. will be rendered as a pseudocolor image. For displaying a grayscale
  4556. image, set up the colormapping using the parameters
  4557. ``cmap='gray', vmin=0, vmax=255``.
  4558. The number of pixels used to render an image is set by the Axes size
  4559. and the figure *dpi*. This can lead to aliasing artifacts when
  4560. the image is resampled, because the displayed image size will usually
  4561. not match the size of *X* (see
  4562. :doc:`/gallery/images_contours_and_fields/image_antialiasing`).
  4563. The resampling can be controlled via the *interpolation* parameter
  4564. and/or :rc:`image.interpolation`.
  4565. Parameters
  4566. ----------
  4567. X : array-like or PIL image
  4568. The image data. Supported array shapes are:
  4569. - (M, N): an image with scalar data. The values are mapped to
  4570. colors using normalization and a colormap. See parameters *norm*,
  4571. *cmap*, *vmin*, *vmax*.
  4572. - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
  4573. - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
  4574. i.e. including transparency.
  4575. The first two dimensions (M, N) define the rows and columns of
  4576. the image.
  4577. Out-of-range RGB(A) values are clipped.
  4578. %(cmap_doc)s
  4579. This parameter is ignored if *X* is RGB(A).
  4580. %(norm_doc)s
  4581. This parameter is ignored if *X* is RGB(A).
  4582. %(vmin_vmax_doc)s
  4583. This parameter is ignored if *X* is RGB(A).
  4584. aspect : {'equal', 'auto'} or float or None, default: None
  4585. The aspect ratio of the Axes. This parameter is particularly
  4586. relevant for images since it determines whether data pixels are
  4587. square.
  4588. This parameter is a shortcut for explicitly calling
  4589. `.Axes.set_aspect`. See there for further details.
  4590. - 'equal': Ensures an aspect ratio of 1. Pixels will be square
  4591. (unless pixel sizes are explicitly made non-square in data
  4592. coordinates using *extent*).
  4593. - 'auto': The Axes is kept fixed and the aspect is adjusted so
  4594. that the data fit in the Axes. In general, this will result in
  4595. non-square pixels.
  4596. Normally, None (the default) means to use :rc:`image.aspect`. However, if
  4597. the image uses a transform that does not contain the axes data transform,
  4598. then None means to not modify the axes aspect at all (in that case, directly
  4599. call `.Axes.set_aspect` if desired).
  4600. interpolation : str, default: :rc:`image.interpolation`
  4601. The interpolation method used.
  4602. Supported values are 'none', 'antialiased', 'nearest', 'bilinear',
  4603. 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
  4604. 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
  4605. 'sinc', 'lanczos', 'blackman'.
  4606. The data *X* is resampled to the pixel size of the image on the
  4607. figure canvas, using the interpolation method to either up- or
  4608. downsample the data.
  4609. If *interpolation* is 'none', then for the ps, pdf, and svg
  4610. backends no down- or upsampling occurs, and the image data is
  4611. passed to the backend as a native image. Note that different ps,
  4612. pdf, and svg viewers may display these raw pixels differently. On
  4613. other backends, 'none' is the same as 'nearest'.
  4614. If *interpolation* is the default 'antialiased', then 'nearest'
  4615. interpolation is used if the image is upsampled by more than a
  4616. factor of three (i.e. the number of display pixels is at least
  4617. three times the size of the data array). If the upsampling rate is
  4618. smaller than 3, or the image is downsampled, then 'hanning'
  4619. interpolation is used to act as an anti-aliasing filter, unless the
  4620. image happens to be upsampled by exactly a factor of two or one.
  4621. See
  4622. :doc:`/gallery/images_contours_and_fields/interpolation_methods`
  4623. for an overview of the supported interpolation methods, and
  4624. :doc:`/gallery/images_contours_and_fields/image_antialiasing` for
  4625. a discussion of image antialiasing.
  4626. Some interpolation methods require an additional radius parameter,
  4627. which can be set by *filterrad*. Additionally, the antigrain image
  4628. resize filter is controlled by the parameter *filternorm*.
  4629. interpolation_stage : {'data', 'rgba'}, default: 'data'
  4630. If 'data', interpolation
  4631. is carried out on the data provided by the user. If 'rgba', the
  4632. interpolation is carried out after the colormapping has been
  4633. applied (visual interpolation).
  4634. alpha : float or array-like, optional
  4635. The alpha blending value, between 0 (transparent) and 1 (opaque).
  4636. If *alpha* is an array, the alpha blending values are applied pixel
  4637. by pixel, and *alpha* must have the same shape as *X*.
  4638. origin : {'upper', 'lower'}, default: :rc:`image.origin`
  4639. Place the [0, 0] index of the array in the upper left or lower
  4640. left corner of the Axes. The convention (the default) 'upper' is
  4641. typically used for matrices and images.
  4642. Note that the vertical axis points upward for 'lower'
  4643. but downward for 'upper'.
  4644. See the :ref:`imshow_extent` tutorial for
  4645. examples and a more detailed description.
  4646. extent : floats (left, right, bottom, top), optional
  4647. The bounding box in data coordinates that the image will fill.
  4648. These values may be unitful and match the units of the Axes.
  4649. The image is stretched individually along x and y to fill the box.
  4650. The default extent is determined by the following conditions.
  4651. Pixels have unit size in data coordinates. Their centers are on
  4652. integer coordinates, and their center coordinates range from 0 to
  4653. columns-1 horizontally and from 0 to rows-1 vertically.
  4654. Note that the direction of the vertical axis and thus the default
  4655. values for top and bottom depend on *origin*:
  4656. - For ``origin == 'upper'`` the default is
  4657. ``(-0.5, numcols-0.5, numrows-0.5, -0.5)``.
  4658. - For ``origin == 'lower'`` the default is
  4659. ``(-0.5, numcols-0.5, -0.5, numrows-0.5)``.
  4660. See the :ref:`imshow_extent` tutorial for
  4661. examples and a more detailed description.
  4662. filternorm : bool, default: True
  4663. A parameter for the antigrain image resize filter (see the
  4664. antigrain documentation). If *filternorm* is set, the filter
  4665. normalizes integer values and corrects the rounding errors. It
  4666. doesn't do anything with the source floating point values, it
  4667. corrects only integers according to the rule of 1.0 which means
  4668. that any sum of pixel weights must be equal to 1.0. So, the
  4669. filter function must produce a graph of the proper shape.
  4670. filterrad : float > 0, default: 4.0
  4671. The filter radius for filters that have a radius parameter, i.e.
  4672. when interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
  4673. resample : bool, default: :rc:`image.resample`
  4674. When *True*, use a full resampling method. When *False*, only
  4675. resample when the output image is larger than the input image.
  4676. url : str, optional
  4677. Set the url of the created `.AxesImage`. See `.Artist.set_url`.
  4678. Returns
  4679. -------
  4680. `~matplotlib.image.AxesImage`
  4681. Other Parameters
  4682. ----------------
  4683. data : indexable object, optional
  4684. DATA_PARAMETER_PLACEHOLDER
  4685. **kwargs : `~matplotlib.artist.Artist` properties
  4686. These parameters are passed on to the constructor of the
  4687. `.AxesImage` artist.
  4688. See Also
  4689. --------
  4690. matshow : Plot a matrix or an array as an image.
  4691. Notes
  4692. -----
  4693. Unless *extent* is used, pixel centers will be located at integer
  4694. coordinates. In other words: the origin will coincide with the center
  4695. of pixel (0, 0).
  4696. There are two common representations for RGB images with an alpha
  4697. channel:
  4698. - Straight (unassociated) alpha: R, G, and B channels represent the
  4699. color of the pixel, disregarding its opacity.
  4700. - Premultiplied (associated) alpha: R, G, and B channels represent
  4701. the color of the pixel, adjusted for its opacity by multiplication.
  4702. `~matplotlib.pyplot.imshow` expects RGB images adopting the straight
  4703. (unassociated) alpha representation.
  4704. """
  4705. im = mimage.AxesImage(self, cmap=cmap, norm=norm,
  4706. interpolation=interpolation, origin=origin,
  4707. extent=extent, filternorm=filternorm,
  4708. filterrad=filterrad, resample=resample,
  4709. interpolation_stage=interpolation_stage,
  4710. **kwargs)
  4711. if aspect is None and not (
  4712. im.is_transform_set()
  4713. and not im.get_transform().contains_branch(self.transData)):
  4714. aspect = mpl.rcParams['image.aspect']
  4715. if aspect is not None:
  4716. self.set_aspect(aspect)
  4717. im.set_data(X)
  4718. im.set_alpha(alpha)
  4719. if im.get_clip_path() is None:
  4720. # image does not already have clipping set, clip to axes patch
  4721. im.set_clip_path(self.patch)
  4722. im._scale_norm(norm, vmin, vmax)
  4723. im.set_url(url)
  4724. # update ax.dataLim, and, if autoscaling, set viewLim
  4725. # to tightly fit the image, regardless of dataLim.
  4726. im.set_extent(im.get_extent())
  4727. self.add_image(im)
  4728. return im
  4729. def _pcolorargs(self, funcname, *args, shading='auto', **kwargs):
  4730. # - create X and Y if not present;
  4731. # - reshape X and Y as needed if they are 1-D;
  4732. # - check for proper sizes based on `shading` kwarg;
  4733. # - reset shading if shading='auto' to flat or nearest
  4734. # depending on size;
  4735. _valid_shading = ['gouraud', 'nearest', 'flat', 'auto']
  4736. try:
  4737. _api.check_in_list(_valid_shading, shading=shading)
  4738. except ValueError:
  4739. _api.warn_external(f"shading value '{shading}' not in list of "
  4740. f"valid values {_valid_shading}. Setting "
  4741. "shading='auto'.")
  4742. shading = 'auto'
  4743. if len(args) == 1:
  4744. C = np.asanyarray(args[0])
  4745. nrows, ncols = C.shape[:2]
  4746. if shading in ['gouraud', 'nearest']:
  4747. X, Y = np.meshgrid(np.arange(ncols), np.arange(nrows))
  4748. else:
  4749. X, Y = np.meshgrid(np.arange(ncols + 1), np.arange(nrows + 1))
  4750. shading = 'flat'
  4751. C = cbook.safe_masked_invalid(C, copy=True)
  4752. return X, Y, C, shading
  4753. if len(args) == 3:
  4754. # Check x and y for bad data...
  4755. C = np.asanyarray(args[2])
  4756. # unit conversion allows e.g. datetime objects as axis values
  4757. X, Y = args[:2]
  4758. X, Y = self._process_unit_info([("x", X), ("y", Y)], kwargs)
  4759. X, Y = [cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]]
  4760. if funcname == 'pcolormesh':
  4761. if np.ma.is_masked(X) or np.ma.is_masked(Y):
  4762. raise ValueError(
  4763. 'x and y arguments to pcolormesh cannot have '
  4764. 'non-finite values or be of type '
  4765. 'numpy.ma.MaskedArray with masked values')
  4766. nrows, ncols = C.shape[:2]
  4767. else:
  4768. raise _api.nargs_error(funcname, takes="1 or 3", given=len(args))
  4769. Nx = X.shape[-1]
  4770. Ny = Y.shape[0]
  4771. if X.ndim != 2 or X.shape[0] == 1:
  4772. x = X.reshape(1, Nx)
  4773. X = x.repeat(Ny, axis=0)
  4774. if Y.ndim != 2 or Y.shape[1] == 1:
  4775. y = Y.reshape(Ny, 1)
  4776. Y = y.repeat(Nx, axis=1)
  4777. if X.shape != Y.shape:
  4778. raise TypeError(f'Incompatible X, Y inputs to {funcname}; '
  4779. f'see help({funcname})')
  4780. if shading == 'auto':
  4781. if ncols == Nx and nrows == Ny:
  4782. shading = 'nearest'
  4783. else:
  4784. shading = 'flat'
  4785. if shading == 'flat':
  4786. if (Nx, Ny) != (ncols + 1, nrows + 1):
  4787. raise TypeError(f"Dimensions of C {C.shape} should"
  4788. f" be one smaller than X({Nx}) and Y({Ny})"
  4789. f" while using shading='flat'"
  4790. f" see help({funcname})")
  4791. else: # ['nearest', 'gouraud']:
  4792. if (Nx, Ny) != (ncols, nrows):
  4793. raise TypeError('Dimensions of C %s are incompatible with'
  4794. ' X (%d) and/or Y (%d); see help(%s)' % (
  4795. C.shape, Nx, Ny, funcname))
  4796. if shading == 'nearest':
  4797. # grid is specified at the center, so define corners
  4798. # at the midpoints between the grid centers and then use the
  4799. # flat algorithm.
  4800. def _interp_grid(X):
  4801. # helper for below
  4802. if np.shape(X)[1] > 1:
  4803. dX = np.diff(X, axis=1)/2.
  4804. if not (np.all(dX >= 0) or np.all(dX <= 0)):
  4805. _api.warn_external(
  4806. f"The input coordinates to {funcname} are "
  4807. "interpreted as cell centers, but are not "
  4808. "monotonically increasing or decreasing. "
  4809. "This may lead to incorrectly calculated cell "
  4810. "edges, in which case, please supply "
  4811. f"explicit cell edges to {funcname}.")
  4812. hstack = np.ma.hstack if np.ma.isMA(X) else np.hstack
  4813. X = hstack((X[:, [0]] - dX[:, [0]],
  4814. X[:, :-1] + dX,
  4815. X[:, [-1]] + dX[:, [-1]]))
  4816. else:
  4817. # This is just degenerate, but we can't reliably guess
  4818. # a dX if there is just one value.
  4819. X = np.hstack((X, X))
  4820. return X
  4821. if ncols == Nx:
  4822. X = _interp_grid(X)
  4823. Y = _interp_grid(Y)
  4824. if nrows == Ny:
  4825. X = _interp_grid(X.T).T
  4826. Y = _interp_grid(Y.T).T
  4827. shading = 'flat'
  4828. C = cbook.safe_masked_invalid(C, copy=True)
  4829. return X, Y, C, shading
  4830. @_preprocess_data()
  4831. @_docstring.dedent_interpd
  4832. def pcolor(self, *args, shading=None, alpha=None, norm=None, cmap=None,
  4833. vmin=None, vmax=None, **kwargs):
  4834. r"""
  4835. Create a pseudocolor plot with a non-regular rectangular grid.
  4836. Call signature::
  4837. pcolor([X, Y,] C, **kwargs)
  4838. *X* and *Y* can be used to specify the corners of the quadrilaterals.
  4839. .. hint::
  4840. ``pcolor()`` can be very slow for large arrays. In most
  4841. cases you should use the similar but much faster
  4842. `~.Axes.pcolormesh` instead. See
  4843. :ref:`Differences between pcolor() and pcolormesh()
  4844. <differences-pcolor-pcolormesh>` for a discussion of the
  4845. differences.
  4846. Parameters
  4847. ----------
  4848. C : 2D array-like
  4849. The color-mapped values. Color-mapping is controlled by *cmap*,
  4850. *norm*, *vmin*, and *vmax*.
  4851. X, Y : array-like, optional
  4852. The coordinates of the corners of quadrilaterals of a pcolormesh::
  4853. (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1])
  4854. ●╶───╴●
  4855. │ │
  4856. ●╶───╴●
  4857. (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])
  4858. Note that the column index corresponds to the x-coordinate, and
  4859. the row index corresponds to y. For details, see the
  4860. :ref:`Notes <axes-pcolormesh-grid-orientation>` section below.
  4861. If ``shading='flat'`` the dimensions of *X* and *Y* should be one
  4862. greater than those of *C*, and the quadrilateral is colored due
  4863. to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal
  4864. dimensions, a warning will be raised and the last row and column
  4865. of *C* will be ignored.
  4866. If ``shading='nearest'``, the dimensions of *X* and *Y* should be
  4867. the same as those of *C* (if not, a ValueError will be raised). The
  4868. color ``C[i, j]`` will be centered on ``(X[i, j], Y[i, j])``.
  4869. If *X* and/or *Y* are 1-D arrays or column vectors they will be
  4870. expanded as needed into the appropriate 2D arrays, making a
  4871. rectangular grid.
  4872. shading : {'flat', 'nearest', 'auto'}, default: :rc:`pcolor.shading`
  4873. The fill style for the quadrilateral. Possible values:
  4874. - 'flat': A solid color is used for each quad. The color of the
  4875. quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by
  4876. ``C[i, j]``. The dimensions of *X* and *Y* should be
  4877. one greater than those of *C*; if they are the same as *C*,
  4878. then a deprecation warning is raised, and the last row
  4879. and column of *C* are dropped.
  4880. - 'nearest': Each grid point will have a color centered on it,
  4881. extending halfway between the adjacent grid centers. The
  4882. dimensions of *X* and *Y* must be the same as *C*.
  4883. - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one
  4884. larger than *C*. Choose 'nearest' if dimensions are the same.
  4885. See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids`
  4886. for more description.
  4887. %(cmap_doc)s
  4888. %(norm_doc)s
  4889. %(vmin_vmax_doc)s
  4890. edgecolors : {'none', None, 'face', color, color sequence}, optional
  4891. The color of the edges. Defaults to 'none'. Possible values:
  4892. - 'none' or '': No edge.
  4893. - *None*: :rc:`patch.edgecolor` will be used. Note that currently
  4894. :rc:`patch.force_edgecolor` has to be True for this to work.
  4895. - 'face': Use the adjacent face color.
  4896. - A color or sequence of colors will set the edge color.
  4897. The singular form *edgecolor* works as an alias.
  4898. alpha : float, default: None
  4899. The alpha blending value of the face color, between 0 (transparent)
  4900. and 1 (opaque). Note: The edgecolor is currently not affected by
  4901. this.
  4902. snap : bool, default: False
  4903. Whether to snap the mesh to pixel boundaries.
  4904. Returns
  4905. -------
  4906. `matplotlib.collections.PolyQuadMesh`
  4907. Other Parameters
  4908. ----------------
  4909. antialiaseds : bool, default: False
  4910. The default *antialiaseds* is False if the default
  4911. *edgecolors*\ ="none" is used. This eliminates artificial lines
  4912. at patch boundaries, and works regardless of the value of alpha.
  4913. If *edgecolors* is not "none", then the default *antialiaseds*
  4914. is taken from :rc:`patch.antialiased`.
  4915. Stroking the edges may be preferred if *alpha* is 1, but will
  4916. cause artifacts otherwise.
  4917. data : indexable object, optional
  4918. DATA_PARAMETER_PLACEHOLDER
  4919. **kwargs
  4920. Additionally, the following arguments are allowed. They are passed
  4921. along to the `~matplotlib.collections.PolyQuadMesh` constructor:
  4922. %(PolyCollection:kwdoc)s
  4923. See Also
  4924. --------
  4925. pcolormesh : for an explanation of the differences between
  4926. pcolor and pcolormesh.
  4927. imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a
  4928. faster alternative.
  4929. Notes
  4930. -----
  4931. **Masked arrays**
  4932. *X*, *Y* and *C* may be masked arrays. If either ``C[i, j]``, or one
  4933. of the vertices surrounding ``C[i, j]`` (*X* or *Y* at
  4934. ``[i, j], [i+1, j], [i, j+1], [i+1, j+1]``) is masked, nothing is
  4935. plotted.
  4936. .. _axes-pcolor-grid-orientation:
  4937. **Grid orientation**
  4938. The grid orientation follows the standard matrix convention: An array
  4939. *C* with shape (nrows, ncolumns) is plotted with the column number as
  4940. *X* and the row number as *Y*.
  4941. """
  4942. if shading is None:
  4943. shading = mpl.rcParams['pcolor.shading']
  4944. shading = shading.lower()
  4945. X, Y, C, shading = self._pcolorargs('pcolor', *args, shading=shading,
  4946. kwargs=kwargs)
  4947. linewidths = (0.25,)
  4948. if 'linewidth' in kwargs:
  4949. kwargs['linewidths'] = kwargs.pop('linewidth')
  4950. kwargs.setdefault('linewidths', linewidths)
  4951. if 'edgecolor' in kwargs:
  4952. kwargs['edgecolors'] = kwargs.pop('edgecolor')
  4953. ec = kwargs.setdefault('edgecolors', 'none')
  4954. # aa setting will default via collections to patch.antialiased
  4955. # unless the boundary is not stroked, in which case the
  4956. # default will be False; with unstroked boundaries, aa
  4957. # makes artifacts that are often disturbing.
  4958. if 'antialiaseds' in kwargs:
  4959. kwargs['antialiased'] = kwargs.pop('antialiaseds')
  4960. if 'antialiased' not in kwargs and cbook._str_lower_equal(ec, "none"):
  4961. kwargs['antialiased'] = False
  4962. kwargs.setdefault('snap', False)
  4963. if np.ma.isMaskedArray(X) or np.ma.isMaskedArray(Y):
  4964. stack = np.ma.stack
  4965. X = np.ma.asarray(X)
  4966. Y = np.ma.asarray(Y)
  4967. # For bounds collections later
  4968. x = X.compressed()
  4969. y = Y.compressed()
  4970. else:
  4971. stack = np.stack
  4972. x = X
  4973. y = Y
  4974. coords = stack([X, Y], axis=-1)
  4975. collection = mcoll.PolyQuadMesh(
  4976. coords, array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs)
  4977. collection._scale_norm(norm, vmin, vmax)
  4978. # Transform from native to data coordinates?
  4979. t = collection._transform
  4980. if (not isinstance(t, mtransforms.Transform) and
  4981. hasattr(t, '_as_mpl_transform')):
  4982. t = t._as_mpl_transform(self.axes)
  4983. if t and any(t.contains_branch_seperately(self.transData)):
  4984. trans_to_data = t - self.transData
  4985. pts = np.vstack([x, y]).T.astype(float)
  4986. transformed_pts = trans_to_data.transform(pts)
  4987. x = transformed_pts[..., 0]
  4988. y = transformed_pts[..., 1]
  4989. self.add_collection(collection, autolim=False)
  4990. minx = np.min(x)
  4991. maxx = np.max(x)
  4992. miny = np.min(y)
  4993. maxy = np.max(y)
  4994. collection.sticky_edges.x[:] = [minx, maxx]
  4995. collection.sticky_edges.y[:] = [miny, maxy]
  4996. corners = (minx, miny), (maxx, maxy)
  4997. self.update_datalim(corners)
  4998. self._request_autoscale_view()
  4999. return collection
  5000. @_preprocess_data()
  5001. @_docstring.dedent_interpd
  5002. def pcolormesh(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
  5003. vmax=None, shading=None, antialiased=False, **kwargs):
  5004. """
  5005. Create a pseudocolor plot with a non-regular rectangular grid.
  5006. Call signature::
  5007. pcolormesh([X, Y,] C, **kwargs)
  5008. *X* and *Y* can be used to specify the corners of the quadrilaterals.
  5009. .. hint::
  5010. `~.Axes.pcolormesh` is similar to `~.Axes.pcolor`. It is much faster
  5011. and preferred in most cases. For a detailed discussion on the
  5012. differences see :ref:`Differences between pcolor() and pcolormesh()
  5013. <differences-pcolor-pcolormesh>`.
  5014. Parameters
  5015. ----------
  5016. C : array-like
  5017. The mesh data. Supported array shapes are:
  5018. - (M, N) or M*N: a mesh with scalar data. The values are mapped to
  5019. colors using normalization and a colormap. See parameters *norm*,
  5020. *cmap*, *vmin*, *vmax*.
  5021. - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
  5022. - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
  5023. i.e. including transparency.
  5024. The first two dimensions (M, N) define the rows and columns of
  5025. the mesh data.
  5026. X, Y : array-like, optional
  5027. The coordinates of the corners of quadrilaterals of a pcolormesh::
  5028. (X[i+1, j], Y[i+1, j]) (X[i+1, j+1], Y[i+1, j+1])
  5029. ●╶───╴●
  5030. │ │
  5031. ●╶───╴●
  5032. (X[i, j], Y[i, j]) (X[i, j+1], Y[i, j+1])
  5033. Note that the column index corresponds to the x-coordinate, and
  5034. the row index corresponds to y. For details, see the
  5035. :ref:`Notes <axes-pcolormesh-grid-orientation>` section below.
  5036. If ``shading='flat'`` the dimensions of *X* and *Y* should be one
  5037. greater than those of *C*, and the quadrilateral is colored due
  5038. to the value at ``C[i, j]``. If *X*, *Y* and *C* have equal
  5039. dimensions, a warning will be raised and the last row and column
  5040. of *C* will be ignored.
  5041. If ``shading='nearest'`` or ``'gouraud'``, the dimensions of *X*
  5042. and *Y* should be the same as those of *C* (if not, a ValueError
  5043. will be raised). For ``'nearest'`` the color ``C[i, j]`` is
  5044. centered on ``(X[i, j], Y[i, j])``. For ``'gouraud'``, a smooth
  5045. interpolation is caried out between the quadrilateral corners.
  5046. If *X* and/or *Y* are 1-D arrays or column vectors they will be
  5047. expanded as needed into the appropriate 2D arrays, making a
  5048. rectangular grid.
  5049. %(cmap_doc)s
  5050. %(norm_doc)s
  5051. %(vmin_vmax_doc)s
  5052. edgecolors : {'none', None, 'face', color, color sequence}, optional
  5053. The color of the edges. Defaults to 'none'. Possible values:
  5054. - 'none' or '': No edge.
  5055. - *None*: :rc:`patch.edgecolor` will be used. Note that currently
  5056. :rc:`patch.force_edgecolor` has to be True for this to work.
  5057. - 'face': Use the adjacent face color.
  5058. - A color or sequence of colors will set the edge color.
  5059. The singular form *edgecolor* works as an alias.
  5060. alpha : float, default: None
  5061. The alpha blending value, between 0 (transparent) and 1 (opaque).
  5062. shading : {'flat', 'nearest', 'gouraud', 'auto'}, optional
  5063. The fill style for the quadrilateral; defaults to
  5064. :rc:`pcolor.shading`. Possible values:
  5065. - 'flat': A solid color is used for each quad. The color of the
  5066. quad (i, j), (i+1, j), (i, j+1), (i+1, j+1) is given by
  5067. ``C[i, j]``. The dimensions of *X* and *Y* should be
  5068. one greater than those of *C*; if they are the same as *C*,
  5069. then a deprecation warning is raised, and the last row
  5070. and column of *C* are dropped.
  5071. - 'nearest': Each grid point will have a color centered on it,
  5072. extending halfway between the adjacent grid centers. The
  5073. dimensions of *X* and *Y* must be the same as *C*.
  5074. - 'gouraud': Each quad will be Gouraud shaded: The color of the
  5075. corners (i', j') are given by ``C[i', j']``. The color values of
  5076. the area in between is interpolated from the corner values.
  5077. The dimensions of *X* and *Y* must be the same as *C*. When
  5078. Gouraud shading is used, *edgecolors* is ignored.
  5079. - 'auto': Choose 'flat' if dimensions of *X* and *Y* are one
  5080. larger than *C*. Choose 'nearest' if dimensions are the same.
  5081. See :doc:`/gallery/images_contours_and_fields/pcolormesh_grids`
  5082. for more description.
  5083. snap : bool, default: False
  5084. Whether to snap the mesh to pixel boundaries.
  5085. rasterized : bool, optional
  5086. Rasterize the pcolormesh when drawing vector graphics. This can
  5087. speed up rendering and produce smaller files for large data sets.
  5088. See also :doc:`/gallery/misc/rasterization_demo`.
  5089. Returns
  5090. -------
  5091. `matplotlib.collections.QuadMesh`
  5092. Other Parameters
  5093. ----------------
  5094. data : indexable object, optional
  5095. DATA_PARAMETER_PLACEHOLDER
  5096. **kwargs
  5097. Additionally, the following arguments are allowed. They are passed
  5098. along to the `~matplotlib.collections.QuadMesh` constructor:
  5099. %(QuadMesh:kwdoc)s
  5100. See Also
  5101. --------
  5102. pcolor : An alternative implementation with slightly different
  5103. features. For a detailed discussion on the differences see
  5104. :ref:`Differences between pcolor() and pcolormesh()
  5105. <differences-pcolor-pcolormesh>`.
  5106. imshow : If *X* and *Y* are each equidistant, `~.Axes.imshow` can be a
  5107. faster alternative.
  5108. Notes
  5109. -----
  5110. **Masked arrays**
  5111. *C* may be a masked array. If ``C[i, j]`` is masked, the corresponding
  5112. quadrilateral will be transparent. Masking of *X* and *Y* is not
  5113. supported. Use `~.Axes.pcolor` if you need this functionality.
  5114. .. _axes-pcolormesh-grid-orientation:
  5115. **Grid orientation**
  5116. The grid orientation follows the standard matrix convention: An array
  5117. *C* with shape (nrows, ncolumns) is plotted with the column number as
  5118. *X* and the row number as *Y*.
  5119. .. _differences-pcolor-pcolormesh:
  5120. **Differences between pcolor() and pcolormesh()**
  5121. Both methods are used to create a pseudocolor plot of a 2D array
  5122. using quadrilaterals.
  5123. The main difference lies in the created object and internal data
  5124. handling:
  5125. While `~.Axes.pcolor` returns a `.PolyQuadMesh`, `~.Axes.pcolormesh`
  5126. returns a `.QuadMesh`. The latter is more specialized for the given
  5127. purpose and thus is faster. It should almost always be preferred.
  5128. There is also a slight difference in the handling of masked arrays.
  5129. Both `~.Axes.pcolor` and `~.Axes.pcolormesh` support masked arrays
  5130. for *C*. However, only `~.Axes.pcolor` supports masked arrays for *X*
  5131. and *Y*. The reason lies in the internal handling of the masked values.
  5132. `~.Axes.pcolor` leaves out the respective polygons from the
  5133. PolyQuadMesh. `~.Axes.pcolormesh` sets the facecolor of the masked
  5134. elements to transparent. You can see the difference when using
  5135. edgecolors. While all edges are drawn irrespective of masking in a
  5136. QuadMesh, the edge between two adjacent masked quadrilaterals in
  5137. `~.Axes.pcolor` is not drawn as the corresponding polygons do not
  5138. exist in the PolyQuadMesh. Because PolyQuadMesh draws each individual
  5139. polygon, it also supports applying hatches and linestyles to the collection.
  5140. Another difference is the support of Gouraud shading in
  5141. `~.Axes.pcolormesh`, which is not available with `~.Axes.pcolor`.
  5142. """
  5143. if shading is None:
  5144. shading = mpl.rcParams['pcolor.shading']
  5145. shading = shading.lower()
  5146. kwargs.setdefault('edgecolors', 'none')
  5147. X, Y, C, shading = self._pcolorargs('pcolormesh', *args,
  5148. shading=shading, kwargs=kwargs)
  5149. coords = np.stack([X, Y], axis=-1)
  5150. kwargs.setdefault('snap', mpl.rcParams['pcolormesh.snap'])
  5151. collection = mcoll.QuadMesh(
  5152. coords, antialiased=antialiased, shading=shading,
  5153. array=C, cmap=cmap, norm=norm, alpha=alpha, **kwargs)
  5154. collection._scale_norm(norm, vmin, vmax)
  5155. coords = coords.reshape(-1, 2) # flatten the grid structure; keep x, y
  5156. # Transform from native to data coordinates?
  5157. t = collection._transform
  5158. if (not isinstance(t, mtransforms.Transform) and
  5159. hasattr(t, '_as_mpl_transform')):
  5160. t = t._as_mpl_transform(self.axes)
  5161. if t and any(t.contains_branch_seperately(self.transData)):
  5162. trans_to_data = t - self.transData
  5163. coords = trans_to_data.transform(coords)
  5164. self.add_collection(collection, autolim=False)
  5165. minx, miny = np.min(coords, axis=0)
  5166. maxx, maxy = np.max(coords, axis=0)
  5167. collection.sticky_edges.x[:] = [minx, maxx]
  5168. collection.sticky_edges.y[:] = [miny, maxy]
  5169. corners = (minx, miny), (maxx, maxy)
  5170. self.update_datalim(corners)
  5171. self._request_autoscale_view()
  5172. return collection
  5173. @_preprocess_data()
  5174. @_docstring.dedent_interpd
  5175. def pcolorfast(self, *args, alpha=None, norm=None, cmap=None, vmin=None,
  5176. vmax=None, **kwargs):
  5177. """
  5178. Create a pseudocolor plot with a non-regular rectangular grid.
  5179. Call signature::
  5180. ax.pcolorfast([X, Y], C, /, **kwargs)
  5181. This method is similar to `~.Axes.pcolor` and `~.Axes.pcolormesh`.
  5182. It's designed to provide the fastest pcolor-type plotting with the
  5183. Agg backend. To achieve this, it uses different algorithms internally
  5184. depending on the complexity of the input grid (regular rectangular,
  5185. non-regular rectangular or arbitrary quadrilateral).
  5186. .. warning::
  5187. This method is experimental. Compared to `~.Axes.pcolor` or
  5188. `~.Axes.pcolormesh` it has some limitations:
  5189. - It supports only flat shading (no outlines)
  5190. - It lacks support for log scaling of the axes.
  5191. - It does not have a pyplot wrapper.
  5192. Parameters
  5193. ----------
  5194. C : array-like
  5195. The image data. Supported array shapes are:
  5196. - (M, N): an image with scalar data. Color-mapping is controlled
  5197. by *cmap*, *norm*, *vmin*, and *vmax*.
  5198. - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
  5199. - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
  5200. i.e. including transparency.
  5201. The first two dimensions (M, N) define the rows and columns of
  5202. the image.
  5203. This parameter can only be passed positionally.
  5204. X, Y : tuple or array-like, default: ``(0, N)``, ``(0, M)``
  5205. *X* and *Y* are used to specify the coordinates of the
  5206. quadrilaterals. There are different ways to do this:
  5207. - Use tuples ``X=(xmin, xmax)`` and ``Y=(ymin, ymax)`` to define
  5208. a *uniform rectangular grid*.
  5209. The tuples define the outer edges of the grid. All individual
  5210. quadrilaterals will be of the same size. This is the fastest
  5211. version.
  5212. - Use 1D arrays *X*, *Y* to specify a *non-uniform rectangular
  5213. grid*.
  5214. In this case *X* and *Y* have to be monotonic 1D arrays of length
  5215. *N+1* and *M+1*, specifying the x and y boundaries of the cells.
  5216. The speed is intermediate. Note: The grid is checked, and if
  5217. found to be uniform the fast version is used.
  5218. - Use 2D arrays *X*, *Y* if you need an *arbitrary quadrilateral
  5219. grid* (i.e. if the quadrilaterals are not rectangular).
  5220. In this case *X* and *Y* are 2D arrays with shape (M + 1, N + 1),
  5221. specifying the x and y coordinates of the corners of the colored
  5222. quadrilaterals.
  5223. This is the most general, but the slowest to render. It may
  5224. produce faster and more compact output using ps, pdf, and
  5225. svg backends, however.
  5226. These arguments can only be passed positionally.
  5227. %(cmap_doc)s
  5228. This parameter is ignored if *C* is RGB(A).
  5229. %(norm_doc)s
  5230. This parameter is ignored if *C* is RGB(A).
  5231. %(vmin_vmax_doc)s
  5232. This parameter is ignored if *C* is RGB(A).
  5233. alpha : float, default: None
  5234. The alpha blending value, between 0 (transparent) and 1 (opaque).
  5235. snap : bool, default: False
  5236. Whether to snap the mesh to pixel boundaries.
  5237. Returns
  5238. -------
  5239. `.AxesImage` or `.PcolorImage` or `.QuadMesh`
  5240. The return type depends on the type of grid:
  5241. - `.AxesImage` for a regular rectangular grid.
  5242. - `.PcolorImage` for a non-regular rectangular grid.
  5243. - `.QuadMesh` for a non-rectangular grid.
  5244. Other Parameters
  5245. ----------------
  5246. data : indexable object, optional
  5247. DATA_PARAMETER_PLACEHOLDER
  5248. **kwargs
  5249. Supported additional parameters depend on the type of grid.
  5250. See return types of *image* for further description.
  5251. """
  5252. C = args[-1]
  5253. nr, nc = np.shape(C)[:2]
  5254. if len(args) == 1:
  5255. style = "image"
  5256. x = [0, nc]
  5257. y = [0, nr]
  5258. elif len(args) == 3:
  5259. x, y = args[:2]
  5260. x = np.asarray(x)
  5261. y = np.asarray(y)
  5262. if x.ndim == 1 and y.ndim == 1:
  5263. if x.size == 2 and y.size == 2:
  5264. style = "image"
  5265. else:
  5266. dx = np.diff(x)
  5267. dy = np.diff(y)
  5268. if (np.ptp(dx) < 0.01 * abs(dx.mean()) and
  5269. np.ptp(dy) < 0.01 * abs(dy.mean())):
  5270. style = "image"
  5271. else:
  5272. style = "pcolorimage"
  5273. elif x.ndim == 2 and y.ndim == 2:
  5274. style = "quadmesh"
  5275. else:
  5276. raise TypeError("arguments do not match valid signatures")
  5277. else:
  5278. raise _api.nargs_error('pcolorfast', '1 or 3', len(args))
  5279. if style == "quadmesh":
  5280. # data point in each cell is value at lower left corner
  5281. coords = np.stack([x, y], axis=-1)
  5282. if np.ndim(C) not in {2, 3}:
  5283. raise ValueError("C must be 2D or 3D")
  5284. collection = mcoll.QuadMesh(
  5285. coords, array=C,
  5286. alpha=alpha, cmap=cmap, norm=norm,
  5287. antialiased=False, edgecolors="none")
  5288. self.add_collection(collection, autolim=False)
  5289. xl, xr, yb, yt = x.min(), x.max(), y.min(), y.max()
  5290. ret = collection
  5291. else: # It's one of the two image styles.
  5292. extent = xl, xr, yb, yt = x[0], x[-1], y[0], y[-1]
  5293. if style == "image":
  5294. im = mimage.AxesImage(
  5295. self, cmap=cmap, norm=norm,
  5296. data=C, alpha=alpha, extent=extent,
  5297. interpolation='nearest', origin='lower',
  5298. **kwargs)
  5299. elif style == "pcolorimage":
  5300. im = mimage.PcolorImage(
  5301. self, x, y, C,
  5302. cmap=cmap, norm=norm, alpha=alpha, extent=extent,
  5303. **kwargs)
  5304. self.add_image(im)
  5305. ret = im
  5306. if np.ndim(C) == 2: # C.ndim == 3 is RGB(A) so doesn't need scaling.
  5307. ret._scale_norm(norm, vmin, vmax)
  5308. if ret.get_clip_path() is None:
  5309. # image does not already have clipping set, clip to axes patch
  5310. ret.set_clip_path(self.patch)
  5311. ret.sticky_edges.x[:] = [xl, xr]
  5312. ret.sticky_edges.y[:] = [yb, yt]
  5313. self.update_datalim(np.array([[xl, yb], [xr, yt]]))
  5314. self._request_autoscale_view(tight=True)
  5315. return ret
  5316. @_preprocess_data()
  5317. @_docstring.dedent_interpd
  5318. def contour(self, *args, **kwargs):
  5319. """
  5320. Plot contour lines.
  5321. Call signature::
  5322. contour([X, Y,] Z, [levels], **kwargs)
  5323. %(contour_doc)s
  5324. """
  5325. kwargs['filled'] = False
  5326. contours = mcontour.QuadContourSet(self, *args, **kwargs)
  5327. self._request_autoscale_view()
  5328. return contours
  5329. @_preprocess_data()
  5330. @_docstring.dedent_interpd
  5331. def contourf(self, *args, **kwargs):
  5332. """
  5333. Plot filled contours.
  5334. Call signature::
  5335. contourf([X, Y,] Z, [levels], **kwargs)
  5336. %(contour_doc)s
  5337. """
  5338. kwargs['filled'] = True
  5339. contours = mcontour.QuadContourSet(self, *args, **kwargs)
  5340. self._request_autoscale_view()
  5341. return contours
  5342. def clabel(self, CS, levels=None, **kwargs):
  5343. """
  5344. Label a contour plot.
  5345. Adds labels to line contours in given `.ContourSet`.
  5346. Parameters
  5347. ----------
  5348. CS : `.ContourSet` instance
  5349. Line contours to label.
  5350. levels : array-like, optional
  5351. A list of level values, that should be labeled. The list must be
  5352. a subset of ``CS.levels``. If not given, all levels are labeled.
  5353. **kwargs
  5354. All other parameters are documented in `~.ContourLabeler.clabel`.
  5355. """
  5356. return CS.clabel(levels, **kwargs)
  5357. #### Data analysis
  5358. @_preprocess_data(replace_names=["x", 'weights'], label_namer="x")
  5359. def hist(self, x, bins=None, range=None, density=False, weights=None,
  5360. cumulative=False, bottom=None, histtype='bar', align='mid',
  5361. orientation='vertical', rwidth=None, log=False,
  5362. color=None, label=None, stacked=False, **kwargs):
  5363. """
  5364. Compute and plot a histogram.
  5365. This method uses `numpy.histogram` to bin the data in *x* and count the
  5366. number of values in each bin, then draws the distribution either as a
  5367. `.BarContainer` or `.Polygon`. The *bins*, *range*, *density*, and
  5368. *weights* parameters are forwarded to `numpy.histogram`.
  5369. If the data has already been binned and counted, use `~.bar` or
  5370. `~.stairs` to plot the distribution::
  5371. counts, bins = np.histogram(x)
  5372. plt.stairs(counts, bins)
  5373. Alternatively, plot pre-computed bins and counts using ``hist()`` by
  5374. treating each bin as a single point with a weight equal to its count::
  5375. plt.hist(bins[:-1], bins, weights=counts)
  5376. The data input *x* can be a singular array, a list of datasets of
  5377. potentially different lengths ([*x0*, *x1*, ...]), or a 2D ndarray in
  5378. which each column is a dataset. Note that the ndarray form is
  5379. transposed relative to the list form. If the input is an array, then
  5380. the return value is a tuple (*n*, *bins*, *patches*); if the input is a
  5381. sequence of arrays, then the return value is a tuple
  5382. ([*n0*, *n1*, ...], *bins*, [*patches0*, *patches1*, ...]).
  5383. Masked arrays are not supported.
  5384. Parameters
  5385. ----------
  5386. x : (n,) array or sequence of (n,) arrays
  5387. Input values, this takes either a single array or a sequence of
  5388. arrays which are not required to be of the same length.
  5389. bins : int or sequence or str, default: :rc:`hist.bins`
  5390. If *bins* is an integer, it defines the number of equal-width bins
  5391. in the range.
  5392. If *bins* is a sequence, it defines the bin edges, including the
  5393. left edge of the first bin and the right edge of the last bin;
  5394. in this case, bins may be unequally spaced. All but the last
  5395. (righthand-most) bin is half-open. In other words, if *bins* is::
  5396. [1, 2, 3, 4]
  5397. then the first bin is ``[1, 2)`` (including 1, but excluding 2) and
  5398. the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which
  5399. *includes* 4.
  5400. If *bins* is a string, it is one of the binning strategies
  5401. supported by `numpy.histogram_bin_edges`: 'auto', 'fd', 'doane',
  5402. 'scott', 'stone', 'rice', 'sturges', or 'sqrt'.
  5403. range : tuple or None, default: None
  5404. The lower and upper range of the bins. Lower and upper outliers
  5405. are ignored. If not provided, *range* is ``(x.min(), x.max())``.
  5406. Range has no effect if *bins* is a sequence.
  5407. If *bins* is a sequence or *range* is specified, autoscaling
  5408. is based on the specified bin range instead of the
  5409. range of x.
  5410. density : bool, default: False
  5411. If ``True``, draw and return a probability density: each bin
  5412. will display the bin's raw count divided by the total number of
  5413. counts *and the bin width*
  5414. (``density = counts / (sum(counts) * np.diff(bins))``),
  5415. so that the area under the histogram integrates to 1
  5416. (``np.sum(density * np.diff(bins)) == 1``).
  5417. If *stacked* is also ``True``, the sum of the histograms is
  5418. normalized to 1.
  5419. weights : (n,) array-like or None, default: None
  5420. An array of weights, of the same shape as *x*. Each value in
  5421. *x* only contributes its associated weight towards the bin count
  5422. (instead of 1). If *density* is ``True``, the weights are
  5423. normalized, so that the integral of the density over the range
  5424. remains 1.
  5425. cumulative : bool or -1, default: False
  5426. If ``True``, then a histogram is computed where each bin gives the
  5427. counts in that bin plus all bins for smaller values. The last bin
  5428. gives the total number of datapoints.
  5429. If *density* is also ``True`` then the histogram is normalized such
  5430. that the last bin equals 1.
  5431. If *cumulative* is a number less than 0 (e.g., -1), the direction
  5432. of accumulation is reversed. In this case, if *density* is also
  5433. ``True``, then the histogram is normalized such that the first bin
  5434. equals 1.
  5435. bottom : array-like, scalar, or None, default: None
  5436. Location of the bottom of each bin, i.e. bins are drawn from
  5437. ``bottom`` to ``bottom + hist(x, bins)`` If a scalar, the bottom
  5438. of each bin is shifted by the same amount. If an array, each bin
  5439. is shifted independently and the length of bottom must match the
  5440. number of bins. If None, defaults to 0.
  5441. histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, default: 'bar'
  5442. The type of histogram to draw.
  5443. - 'bar' is a traditional bar-type histogram. If multiple data
  5444. are given the bars are arranged side by side.
  5445. - 'barstacked' is a bar-type histogram where multiple
  5446. data are stacked on top of each other.
  5447. - 'step' generates a lineplot that is by default unfilled.
  5448. - 'stepfilled' generates a lineplot that is by default filled.
  5449. align : {'left', 'mid', 'right'}, default: 'mid'
  5450. The horizontal alignment of the histogram bars.
  5451. - 'left': bars are centered on the left bin edges.
  5452. - 'mid': bars are centered between the bin edges.
  5453. - 'right': bars are centered on the right bin edges.
  5454. orientation : {'vertical', 'horizontal'}, default: 'vertical'
  5455. If 'horizontal', `~.Axes.barh` will be used for bar-type histograms
  5456. and the *bottom* kwarg will be the left edges.
  5457. rwidth : float or None, default: None
  5458. The relative width of the bars as a fraction of the bin width. If
  5459. ``None``, automatically compute the width.
  5460. Ignored if *histtype* is 'step' or 'stepfilled'.
  5461. log : bool, default: False
  5462. If ``True``, the histogram axis will be set to a log scale.
  5463. color : color or array-like of colors or None, default: None
  5464. Color or sequence of colors, one per dataset. Default (``None``)
  5465. uses the standard line color sequence.
  5466. label : str or None, default: None
  5467. String, or sequence of strings to match multiple datasets. Bar
  5468. charts yield multiple patches per dataset, but only the first gets
  5469. the label, so that `~.Axes.legend` will work as expected.
  5470. stacked : bool, default: False
  5471. If ``True``, multiple data are stacked on top of each other If
  5472. ``False`` multiple data are arranged side by side if histtype is
  5473. 'bar' or on top of each other if histtype is 'step'
  5474. Returns
  5475. -------
  5476. n : array or list of arrays
  5477. The values of the histogram bins. See *density* and *weights* for a
  5478. description of the possible semantics. If input *x* is an array,
  5479. then this is an array of length *nbins*. If input is a sequence of
  5480. arrays ``[data1, data2, ...]``, then this is a list of arrays with
  5481. the values of the histograms for each of the arrays in the same
  5482. order. The dtype of the array *n* (or of its element arrays) will
  5483. always be float even if no weighting or normalization is used.
  5484. bins : array
  5485. The edges of the bins. Length nbins + 1 (nbins left edges and right
  5486. edge of last bin). Always a single array even when multiple data
  5487. sets are passed in.
  5488. patches : `.BarContainer` or list of a single `.Polygon` or list of \
  5489. such objects
  5490. Container of individual artists used to create the histogram
  5491. or list of such containers if there are multiple input datasets.
  5492. Other Parameters
  5493. ----------------
  5494. data : indexable object, optional
  5495. DATA_PARAMETER_PLACEHOLDER
  5496. **kwargs
  5497. `~matplotlib.patches.Patch` properties
  5498. See Also
  5499. --------
  5500. hist2d : 2D histogram with rectangular bins
  5501. hexbin : 2D histogram with hexagonal bins
  5502. stairs : Plot a pre-computed histogram
  5503. bar : Plot a pre-computed histogram
  5504. Notes
  5505. -----
  5506. For large numbers of bins (>1000), plotting can be significantly
  5507. accelerated by using `~.Axes.stairs` to plot a pre-computed histogram
  5508. (``plt.stairs(*np.histogram(data))``), or by setting *histtype* to
  5509. 'step' or 'stepfilled' rather than 'bar' or 'barstacked'.
  5510. """
  5511. # Avoid shadowing the builtin.
  5512. bin_range = range
  5513. from builtins import range
  5514. if np.isscalar(x):
  5515. x = [x]
  5516. if bins is None:
  5517. bins = mpl.rcParams['hist.bins']
  5518. # Validate string inputs here to avoid cluttering subsequent code.
  5519. _api.check_in_list(['bar', 'barstacked', 'step', 'stepfilled'],
  5520. histtype=histtype)
  5521. _api.check_in_list(['left', 'mid', 'right'], align=align)
  5522. _api.check_in_list(['horizontal', 'vertical'], orientation=orientation)
  5523. if histtype == 'barstacked' and not stacked:
  5524. stacked = True
  5525. # Massage 'x' for processing.
  5526. x = cbook._reshape_2D(x, 'x')
  5527. nx = len(x) # number of datasets
  5528. # Process unit information. _process_unit_info sets the unit and
  5529. # converts the first dataset; then we convert each following dataset
  5530. # one at a time.
  5531. if orientation == "vertical":
  5532. convert_units = self.convert_xunits
  5533. x = [*self._process_unit_info([("x", x[0])], kwargs),
  5534. *map(convert_units, x[1:])]
  5535. else: # horizontal
  5536. convert_units = self.convert_yunits
  5537. x = [*self._process_unit_info([("y", x[0])], kwargs),
  5538. *map(convert_units, x[1:])]
  5539. if bin_range is not None:
  5540. bin_range = convert_units(bin_range)
  5541. if not cbook.is_scalar_or_string(bins):
  5542. bins = convert_units(bins)
  5543. # We need to do to 'weights' what was done to 'x'
  5544. if weights is not None:
  5545. w = cbook._reshape_2D(weights, 'weights')
  5546. else:
  5547. w = [None] * nx
  5548. if len(w) != nx:
  5549. raise ValueError('weights should have the same shape as x')
  5550. input_empty = True
  5551. for xi, wi in zip(x, w):
  5552. len_xi = len(xi)
  5553. if wi is not None and len(wi) != len_xi:
  5554. raise ValueError('weights should have the same shape as x')
  5555. if len_xi:
  5556. input_empty = False
  5557. if color is None:
  5558. colors = [self._get_lines.get_next_color() for i in range(nx)]
  5559. else:
  5560. colors = mcolors.to_rgba_array(color)
  5561. if len(colors) != nx:
  5562. raise ValueError(f"The 'color' keyword argument must have one "
  5563. f"color per dataset, but {nx} datasets and "
  5564. f"{len(colors)} colors were provided")
  5565. hist_kwargs = dict()
  5566. # if the bin_range is not given, compute without nan numpy
  5567. # does not do this for us when guessing the range (but will
  5568. # happily ignore nans when computing the histogram).
  5569. if bin_range is None:
  5570. xmin = np.inf
  5571. xmax = -np.inf
  5572. for xi in x:
  5573. if len(xi):
  5574. # python's min/max ignore nan,
  5575. # np.minnan returns nan for all nan input
  5576. xmin = min(xmin, np.nanmin(xi))
  5577. xmax = max(xmax, np.nanmax(xi))
  5578. if xmin <= xmax: # Only happens if we have seen a finite value.
  5579. bin_range = (xmin, xmax)
  5580. # If bins are not specified either explicitly or via range,
  5581. # we need to figure out the range required for all datasets,
  5582. # and supply that to np.histogram.
  5583. if not input_empty and len(x) > 1:
  5584. if weights is not None:
  5585. _w = np.concatenate(w)
  5586. else:
  5587. _w = None
  5588. bins = np.histogram_bin_edges(
  5589. np.concatenate(x), bins, bin_range, _w)
  5590. else:
  5591. hist_kwargs['range'] = bin_range
  5592. density = bool(density)
  5593. if density and not stacked:
  5594. hist_kwargs['density'] = density
  5595. # List to store all the top coordinates of the histograms
  5596. tops = [] # Will have shape (n_datasets, n_bins).
  5597. # Loop through datasets
  5598. for i in range(nx):
  5599. # this will automatically overwrite bins,
  5600. # so that each histogram uses the same bins
  5601. m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
  5602. tops.append(m)
  5603. tops = np.array(tops, float) # causes problems later if it's an int
  5604. bins = np.array(bins, float) # causes problems if float16
  5605. if stacked:
  5606. tops = tops.cumsum(axis=0)
  5607. # If a stacked density plot, normalize so the area of all the
  5608. # stacked histograms together is 1
  5609. if density:
  5610. tops = (tops / np.diff(bins)) / tops[-1].sum()
  5611. if cumulative:
  5612. slc = slice(None)
  5613. if isinstance(cumulative, Number) and cumulative < 0:
  5614. slc = slice(None, None, -1)
  5615. if density:
  5616. tops = (tops * np.diff(bins))[:, slc].cumsum(axis=1)[:, slc]
  5617. else:
  5618. tops = tops[:, slc].cumsum(axis=1)[:, slc]
  5619. patches = []
  5620. if histtype.startswith('bar'):
  5621. totwidth = np.diff(bins)
  5622. if rwidth is not None:
  5623. dr = np.clip(rwidth, 0, 1)
  5624. elif (len(tops) > 1 and
  5625. ((not stacked) or mpl.rcParams['_internal.classic_mode'])):
  5626. dr = 0.8
  5627. else:
  5628. dr = 1.0
  5629. if histtype == 'bar' and not stacked:
  5630. width = dr * totwidth / nx
  5631. dw = width
  5632. boffset = -0.5 * dr * totwidth * (1 - 1 / nx)
  5633. elif histtype == 'barstacked' or stacked:
  5634. width = dr * totwidth
  5635. boffset, dw = 0.0, 0.0
  5636. if align == 'mid':
  5637. boffset += 0.5 * totwidth
  5638. elif align == 'right':
  5639. boffset += totwidth
  5640. if orientation == 'horizontal':
  5641. _barfunc = self.barh
  5642. bottom_kwarg = 'left'
  5643. else: # orientation == 'vertical'
  5644. _barfunc = self.bar
  5645. bottom_kwarg = 'bottom'
  5646. for top, color in zip(tops, colors):
  5647. if bottom is None:
  5648. bottom = np.zeros(len(top))
  5649. if stacked:
  5650. height = top - bottom
  5651. else:
  5652. height = top
  5653. bars = _barfunc(bins[:-1]+boffset, height, width,
  5654. align='center', log=log,
  5655. color=color, **{bottom_kwarg: bottom})
  5656. patches.append(bars)
  5657. if stacked:
  5658. bottom = top
  5659. boffset += dw
  5660. # Remove stickies from all bars but the lowest ones, as otherwise
  5661. # margin expansion would be unable to cross the stickies in the
  5662. # middle of the bars.
  5663. for bars in patches[1:]:
  5664. for patch in bars:
  5665. patch.sticky_edges.x[:] = patch.sticky_edges.y[:] = []
  5666. elif histtype.startswith('step'):
  5667. # these define the perimeter of the polygon
  5668. x = np.zeros(4 * len(bins) - 3)
  5669. y = np.zeros(4 * len(bins) - 3)
  5670. x[0:2*len(bins)-1:2], x[1:2*len(bins)-1:2] = bins, bins[:-1]
  5671. x[2*len(bins)-1:] = x[1:2*len(bins)-1][::-1]
  5672. if bottom is None:
  5673. bottom = 0
  5674. y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = bottom
  5675. y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1]
  5676. if log:
  5677. if orientation == 'horizontal':
  5678. self.set_xscale('log', nonpositive='clip')
  5679. else: # orientation == 'vertical'
  5680. self.set_yscale('log', nonpositive='clip')
  5681. if align == 'left':
  5682. x -= 0.5*(bins[1]-bins[0])
  5683. elif align == 'right':
  5684. x += 0.5*(bins[1]-bins[0])
  5685. # If fill kwarg is set, it will be passed to the patch collection,
  5686. # overriding this
  5687. fill = (histtype == 'stepfilled')
  5688. xvals, yvals = [], []
  5689. for top in tops:
  5690. if stacked:
  5691. # top of the previous polygon becomes the bottom
  5692. y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1]
  5693. # set the top of this polygon
  5694. y[1:2*len(bins)-1:2] = y[2:2*len(bins):2] = top + bottom
  5695. # The starting point of the polygon has not yet been
  5696. # updated. So far only the endpoint was adjusted. This
  5697. # assignment closes the polygon. The redundant endpoint is
  5698. # later discarded (for step and stepfilled).
  5699. y[0] = y[-1]
  5700. if orientation == 'horizontal':
  5701. xvals.append(y.copy())
  5702. yvals.append(x.copy())
  5703. else:
  5704. xvals.append(x.copy())
  5705. yvals.append(y.copy())
  5706. # stepfill is closed, step is not
  5707. split = -1 if fill else 2 * len(bins)
  5708. # add patches in reverse order so that when stacking,
  5709. # items lower in the stack are plotted on top of
  5710. # items higher in the stack
  5711. for x, y, color in reversed(list(zip(xvals, yvals, colors))):
  5712. patches.append(self.fill(
  5713. x[:split], y[:split],
  5714. closed=True if fill else None,
  5715. facecolor=color,
  5716. edgecolor=None if fill else color,
  5717. fill=fill if fill else None,
  5718. zorder=None if fill else mlines.Line2D.zorder))
  5719. for patch_list in patches:
  5720. for patch in patch_list:
  5721. if orientation == 'vertical':
  5722. patch.sticky_edges.y.append(0)
  5723. elif orientation == 'horizontal':
  5724. patch.sticky_edges.x.append(0)
  5725. # we return patches, so put it back in the expected order
  5726. patches.reverse()
  5727. # If None, make all labels None (via zip_longest below); otherwise,
  5728. # cast each element to str, but keep a single str as it.
  5729. labels = [] if label is None else np.atleast_1d(np.asarray(label, str))
  5730. for patch, lbl in itertools.zip_longest(patches, labels):
  5731. if patch:
  5732. p = patch[0]
  5733. p._internal_update(kwargs)
  5734. if lbl is not None:
  5735. p.set_label(lbl)
  5736. for p in patch[1:]:
  5737. p._internal_update(kwargs)
  5738. p.set_label('_nolegend_')
  5739. if nx == 1:
  5740. return tops[0], bins, patches[0]
  5741. else:
  5742. patch_type = ("BarContainer" if histtype.startswith("bar")
  5743. else "list[Polygon]")
  5744. return tops, bins, cbook.silent_list(patch_type, patches)
  5745. @_preprocess_data()
  5746. def stairs(self, values, edges=None, *,
  5747. orientation='vertical', baseline=0, fill=False, **kwargs):
  5748. """
  5749. A stepwise constant function as a line with bounding edges
  5750. or a filled plot.
  5751. Parameters
  5752. ----------
  5753. values : array-like
  5754. The step heights.
  5755. edges : array-like
  5756. The edge positions, with ``len(edges) == len(vals) + 1``,
  5757. between which the curve takes on vals values.
  5758. orientation : {'vertical', 'horizontal'}, default: 'vertical'
  5759. The direction of the steps. Vertical means that *values* are along
  5760. the y-axis, and edges are along the x-axis.
  5761. baseline : float, array-like or None, default: 0
  5762. The bottom value of the bounding edges or when
  5763. ``fill=True``, position of lower edge. If *fill* is
  5764. True or an array is passed to *baseline*, a closed
  5765. path is drawn.
  5766. fill : bool, default: False
  5767. Whether the area under the step curve should be filled.
  5768. Returns
  5769. -------
  5770. StepPatch : `~matplotlib.patches.StepPatch`
  5771. Other Parameters
  5772. ----------------
  5773. data : indexable object, optional
  5774. DATA_PARAMETER_PLACEHOLDER
  5775. **kwargs
  5776. `~matplotlib.patches.StepPatch` properties
  5777. """
  5778. if 'color' in kwargs:
  5779. _color = kwargs.pop('color')
  5780. else:
  5781. _color = self._get_lines.get_next_color()
  5782. if fill:
  5783. kwargs.setdefault('linewidth', 0)
  5784. kwargs.setdefault('facecolor', _color)
  5785. else:
  5786. kwargs.setdefault('edgecolor', _color)
  5787. if edges is None:
  5788. edges = np.arange(len(values) + 1)
  5789. edges, values, baseline = self._process_unit_info(
  5790. [("x", edges), ("y", values), ("y", baseline)], kwargs)
  5791. patch = mpatches.StepPatch(values,
  5792. edges,
  5793. baseline=baseline,
  5794. orientation=orientation,
  5795. fill=fill,
  5796. **kwargs)
  5797. self.add_patch(patch)
  5798. if baseline is None:
  5799. baseline = 0
  5800. if orientation == 'vertical':
  5801. patch.sticky_edges.y.append(np.min(baseline))
  5802. self.update_datalim([(edges[0], np.min(baseline))])
  5803. else:
  5804. patch.sticky_edges.x.append(np.min(baseline))
  5805. self.update_datalim([(np.min(baseline), edges[0])])
  5806. self._request_autoscale_view()
  5807. return patch
  5808. @_preprocess_data(replace_names=["x", "y", "weights"])
  5809. @_docstring.dedent_interpd
  5810. def hist2d(self, x, y, bins=10, range=None, density=False, weights=None,
  5811. cmin=None, cmax=None, **kwargs):
  5812. """
  5813. Make a 2D histogram plot.
  5814. Parameters
  5815. ----------
  5816. x, y : array-like, shape (n, )
  5817. Input values
  5818. bins : None or int or [int, int] or array-like or [array, array]
  5819. The bin specification:
  5820. - If int, the number of bins for the two dimensions
  5821. (``nx = ny = bins``).
  5822. - If ``[int, int]``, the number of bins in each dimension
  5823. (``nx, ny = bins``).
  5824. - If array-like, the bin edges for the two dimensions
  5825. (``x_edges = y_edges = bins``).
  5826. - If ``[array, array]``, the bin edges in each dimension
  5827. (``x_edges, y_edges = bins``).
  5828. The default value is 10.
  5829. range : array-like shape(2, 2), optional
  5830. The leftmost and rightmost edges of the bins along each dimension
  5831. (if not specified explicitly in the bins parameters): ``[[xmin,
  5832. xmax], [ymin, ymax]]``. All values outside of this range will be
  5833. considered outliers and not tallied in the histogram.
  5834. density : bool, default: False
  5835. Normalize histogram. See the documentation for the *density*
  5836. parameter of `~.Axes.hist` for more details.
  5837. weights : array-like, shape (n, ), optional
  5838. An array of values w_i weighing each sample (x_i, y_i).
  5839. cmin, cmax : float, default: None
  5840. All bins that has count less than *cmin* or more than *cmax* will not be
  5841. displayed (set to NaN before passing to `~.Axes.pcolormesh`) and these count
  5842. values in the return value count histogram will also be set to nan upon
  5843. return.
  5844. Returns
  5845. -------
  5846. h : 2D array
  5847. The bi-dimensional histogram of samples x and y. Values in x are
  5848. histogrammed along the first dimension and values in y are
  5849. histogrammed along the second dimension.
  5850. xedges : 1D array
  5851. The bin edges along the x-axis.
  5852. yedges : 1D array
  5853. The bin edges along the y-axis.
  5854. image : `~.matplotlib.collections.QuadMesh`
  5855. Other Parameters
  5856. ----------------
  5857. %(cmap_doc)s
  5858. %(norm_doc)s
  5859. %(vmin_vmax_doc)s
  5860. alpha : ``0 <= scalar <= 1`` or ``None``, optional
  5861. The alpha blending value.
  5862. data : indexable object, optional
  5863. DATA_PARAMETER_PLACEHOLDER
  5864. **kwargs
  5865. Additional parameters are passed along to the
  5866. `~.Axes.pcolormesh` method and `~matplotlib.collections.QuadMesh`
  5867. constructor.
  5868. See Also
  5869. --------
  5870. hist : 1D histogram plotting
  5871. hexbin : 2D histogram with hexagonal bins
  5872. Notes
  5873. -----
  5874. - Currently ``hist2d`` calculates its own axis limits, and any limits
  5875. previously set are ignored.
  5876. - Rendering the histogram with a logarithmic color scale is
  5877. accomplished by passing a `.colors.LogNorm` instance to the *norm*
  5878. keyword argument. Likewise, power-law normalization (similar
  5879. in effect to gamma correction) can be accomplished with
  5880. `.colors.PowerNorm`.
  5881. """
  5882. h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range,
  5883. density=density, weights=weights)
  5884. if cmin is not None:
  5885. h[h < cmin] = None
  5886. if cmax is not None:
  5887. h[h > cmax] = None
  5888. pc = self.pcolormesh(xedges, yedges, h.T, **kwargs)
  5889. self.set_xlim(xedges[0], xedges[-1])
  5890. self.set_ylim(yedges[0], yedges[-1])
  5891. return h, xedges, yedges, pc
  5892. @_preprocess_data(replace_names=["x", "weights"], label_namer="x")
  5893. @_docstring.dedent_interpd
  5894. def ecdf(self, x, weights=None, *, complementary=False,
  5895. orientation="vertical", compress=False, **kwargs):
  5896. """
  5897. Compute and plot the empirical cumulative distribution function of *x*.
  5898. .. versionadded:: 3.8
  5899. Parameters
  5900. ----------
  5901. x : 1d array-like
  5902. The input data. Infinite entries are kept (and move the relevant
  5903. end of the ecdf from 0/1), but NaNs and masked values are errors.
  5904. weights : 1d array-like or None, default: None
  5905. The weights of the entries; must have the same shape as *x*.
  5906. Weights corresponding to NaN data points are dropped, and then the
  5907. remaining weights are normalized to sum to 1. If unset, all
  5908. entries have the same weight.
  5909. complementary : bool, default: False
  5910. Whether to plot a cumulative distribution function, which increases
  5911. from 0 to 1 (the default), or a complementary cumulative
  5912. distribution function, which decreases from 1 to 0.
  5913. orientation : {"vertical", "horizontal"}, default: "vertical"
  5914. Whether the entries are plotted along the x-axis ("vertical", the
  5915. default) or the y-axis ("horizontal"). This parameter takes the
  5916. same values as in `~.Axes.hist`.
  5917. compress : bool, default: False
  5918. Whether multiple entries with the same values are grouped together
  5919. (with a summed weight) before plotting. This is mainly useful if
  5920. *x* contains many identical data points, to decrease the rendering
  5921. complexity of the plot. If *x* contains no duplicate points, this
  5922. has no effect and just uses some time and memory.
  5923. Other Parameters
  5924. ----------------
  5925. data : indexable object, optional
  5926. DATA_PARAMETER_PLACEHOLDER
  5927. **kwargs
  5928. Keyword arguments control the `.Line2D` properties:
  5929. %(Line2D:kwdoc)s
  5930. Returns
  5931. -------
  5932. `.Line2D`
  5933. Notes
  5934. -----
  5935. The ecdf plot can be thought of as a cumulative histogram with one bin
  5936. per data entry; i.e. it reports on the entire dataset without any
  5937. arbitrary binning.
  5938. If *x* contains NaNs or masked entries, either remove them first from
  5939. the array (if they should not taken into account), or replace them by
  5940. -inf or +inf (if they should be sorted at the beginning or the end of
  5941. the array).
  5942. """
  5943. _api.check_in_list(["horizontal", "vertical"], orientation=orientation)
  5944. if "drawstyle" in kwargs or "ds" in kwargs:
  5945. raise TypeError("Cannot pass 'drawstyle' or 'ds' to ecdf()")
  5946. if np.ma.getmask(x).any():
  5947. raise ValueError("ecdf() does not support masked entries")
  5948. x = np.asarray(x)
  5949. if np.isnan(x).any():
  5950. raise ValueError("ecdf() does not support NaNs")
  5951. argsort = np.argsort(x)
  5952. x = x[argsort]
  5953. if weights is None:
  5954. # Ensure that we end at exactly 1, avoiding floating point errors.
  5955. cum_weights = (1 + np.arange(len(x))) / len(x)
  5956. else:
  5957. weights = np.take(weights, argsort) # Reorder weights like we reordered x.
  5958. cum_weights = np.cumsum(weights / np.sum(weights))
  5959. if compress:
  5960. # Get indices of unique x values.
  5961. compress_idxs = [0, *(x[:-1] != x[1:]).nonzero()[0] + 1]
  5962. x = x[compress_idxs]
  5963. cum_weights = cum_weights[compress_idxs]
  5964. if orientation == "vertical":
  5965. if not complementary:
  5966. line, = self.plot([x[0], *x], [0, *cum_weights],
  5967. drawstyle="steps-post", **kwargs)
  5968. else:
  5969. line, = self.plot([*x, x[-1]], [1, *1 - cum_weights],
  5970. drawstyle="steps-pre", **kwargs)
  5971. line.sticky_edges.y[:] = [0, 1]
  5972. else: # orientation == "horizontal":
  5973. if not complementary:
  5974. line, = self.plot([0, *cum_weights], [x[0], *x],
  5975. drawstyle="steps-pre", **kwargs)
  5976. else:
  5977. line, = self.plot([1, *1 - cum_weights], [*x, x[-1]],
  5978. drawstyle="steps-post", **kwargs)
  5979. line.sticky_edges.x[:] = [0, 1]
  5980. return line
  5981. @_preprocess_data(replace_names=["x"])
  5982. @_docstring.dedent_interpd
  5983. def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
  5984. window=None, noverlap=None, pad_to=None,
  5985. sides=None, scale_by_freq=None, return_line=None, **kwargs):
  5986. r"""
  5987. Plot the power spectral density.
  5988. The power spectral density :math:`P_{xx}` by Welch's average
  5989. periodogram method. The vector *x* is divided into *NFFT* length
  5990. segments. Each segment is detrended by function *detrend* and
  5991. windowed by function *window*. *noverlap* gives the length of
  5992. the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
  5993. of each segment :math:`i` are averaged to compute :math:`P_{xx}`,
  5994. with a scaling to correct for power loss due to windowing.
  5995. If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
  5996. Parameters
  5997. ----------
  5998. x : 1-D array or sequence
  5999. Array or sequence containing the data
  6000. %(Spectral)s
  6001. %(PSD)s
  6002. noverlap : int, default: 0 (no overlap)
  6003. The number of points of overlap between segments.
  6004. Fc : int, default: 0
  6005. The center frequency of *x*, which offsets the x extents of the
  6006. plot to reflect the frequency range used when a signal is acquired
  6007. and then filtered and downsampled to baseband.
  6008. return_line : bool, default: False
  6009. Whether to include the line object plotted in the returned values.
  6010. Returns
  6011. -------
  6012. Pxx : 1-D array
  6013. The values for the power spectrum :math:`P_{xx}` before scaling
  6014. (real valued).
  6015. freqs : 1-D array
  6016. The frequencies corresponding to the elements in *Pxx*.
  6017. line : `~matplotlib.lines.Line2D`
  6018. The line created by this function.
  6019. Only returned if *return_line* is True.
  6020. Other Parameters
  6021. ----------------
  6022. data : indexable object, optional
  6023. DATA_PARAMETER_PLACEHOLDER
  6024. **kwargs
  6025. Keyword arguments control the `.Line2D` properties:
  6026. %(Line2D:kwdoc)s
  6027. See Also
  6028. --------
  6029. specgram
  6030. Differs in the default overlap; in not returning the mean of the
  6031. segment periodograms; in returning the times of the segments; and
  6032. in plotting a colormap instead of a line.
  6033. magnitude_spectrum
  6034. Plots the magnitude spectrum.
  6035. csd
  6036. Plots the spectral density between two signals.
  6037. Notes
  6038. -----
  6039. For plotting, the power is plotted as
  6040. :math:`10\log_{10}(P_{xx})` for decibels, though *Pxx* itself
  6041. is returned.
  6042. References
  6043. ----------
  6044. Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,
  6045. John Wiley & Sons (1986)
  6046. """
  6047. if Fc is None:
  6048. Fc = 0
  6049. pxx, freqs = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend,
  6050. window=window, noverlap=noverlap, pad_to=pad_to,
  6051. sides=sides, scale_by_freq=scale_by_freq)
  6052. freqs += Fc
  6053. if scale_by_freq in (None, True):
  6054. psd_units = 'dB/Hz'
  6055. else:
  6056. psd_units = 'dB'
  6057. line = self.plot(freqs, 10 * np.log10(pxx), **kwargs)
  6058. self.set_xlabel('Frequency')
  6059. self.set_ylabel('Power Spectral Density (%s)' % psd_units)
  6060. self.grid(True)
  6061. vmin, vmax = self.get_ybound()
  6062. step = max(10 * int(np.log10(vmax - vmin)), 1)
  6063. ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)
  6064. self.set_yticks(ticks)
  6065. if return_line is None or not return_line:
  6066. return pxx, freqs
  6067. else:
  6068. return pxx, freqs, line
  6069. @_preprocess_data(replace_names=["x", "y"], label_namer="y")
  6070. @_docstring.dedent_interpd
  6071. def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None,
  6072. window=None, noverlap=None, pad_to=None,
  6073. sides=None, scale_by_freq=None, return_line=None, **kwargs):
  6074. r"""
  6075. Plot the cross-spectral density.
  6076. The cross spectral density :math:`P_{xy}` by Welch's average
  6077. periodogram method. The vectors *x* and *y* are divided into
  6078. *NFFT* length segments. Each segment is detrended by function
  6079. *detrend* and windowed by function *window*. *noverlap* gives
  6080. the length of the overlap between segments. The product of
  6081. the direct FFTs of *x* and *y* are averaged over each segment
  6082. to compute :math:`P_{xy}`, with a scaling to correct for power
  6083. loss due to windowing.
  6084. If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
  6085. padded to *NFFT*.
  6086. Parameters
  6087. ----------
  6088. x, y : 1-D arrays or sequences
  6089. Arrays or sequences containing the data.
  6090. %(Spectral)s
  6091. %(PSD)s
  6092. noverlap : int, default: 0 (no overlap)
  6093. The number of points of overlap between segments.
  6094. Fc : int, default: 0
  6095. The center frequency of *x*, which offsets the x extents of the
  6096. plot to reflect the frequency range used when a signal is acquired
  6097. and then filtered and downsampled to baseband.
  6098. return_line : bool, default: False
  6099. Whether to include the line object plotted in the returned values.
  6100. Returns
  6101. -------
  6102. Pxy : 1-D array
  6103. The values for the cross spectrum :math:`P_{xy}` before scaling
  6104. (complex valued).
  6105. freqs : 1-D array
  6106. The frequencies corresponding to the elements in *Pxy*.
  6107. line : `~matplotlib.lines.Line2D`
  6108. The line created by this function.
  6109. Only returned if *return_line* is True.
  6110. Other Parameters
  6111. ----------------
  6112. data : indexable object, optional
  6113. DATA_PARAMETER_PLACEHOLDER
  6114. **kwargs
  6115. Keyword arguments control the `.Line2D` properties:
  6116. %(Line2D:kwdoc)s
  6117. See Also
  6118. --------
  6119. psd : is equivalent to setting ``y = x``.
  6120. Notes
  6121. -----
  6122. For plotting, the power is plotted as
  6123. :math:`10 \log_{10}(P_{xy})` for decibels, though :math:`P_{xy}` itself
  6124. is returned.
  6125. References
  6126. ----------
  6127. Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,
  6128. John Wiley & Sons (1986)
  6129. """
  6130. if Fc is None:
  6131. Fc = 0
  6132. pxy, freqs = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend,
  6133. window=window, noverlap=noverlap, pad_to=pad_to,
  6134. sides=sides, scale_by_freq=scale_by_freq)
  6135. # pxy is complex
  6136. freqs += Fc
  6137. line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs)
  6138. self.set_xlabel('Frequency')
  6139. self.set_ylabel('Cross Spectrum Magnitude (dB)')
  6140. self.grid(True)
  6141. vmin, vmax = self.get_ybound()
  6142. step = max(10 * int(np.log10(vmax - vmin)), 1)
  6143. ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)
  6144. self.set_yticks(ticks)
  6145. if return_line is None or not return_line:
  6146. return pxy, freqs
  6147. else:
  6148. return pxy, freqs, line
  6149. @_preprocess_data(replace_names=["x"])
  6150. @_docstring.dedent_interpd
  6151. def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
  6152. pad_to=None, sides=None, scale=None,
  6153. **kwargs):
  6154. """
  6155. Plot the magnitude spectrum.
  6156. Compute the magnitude spectrum of *x*. Data is padded to a
  6157. length of *pad_to* and the windowing function *window* is applied to
  6158. the signal.
  6159. Parameters
  6160. ----------
  6161. x : 1-D array or sequence
  6162. Array or sequence containing the data.
  6163. %(Spectral)s
  6164. %(Single_Spectrum)s
  6165. scale : {'default', 'linear', 'dB'}
  6166. The scaling of the values in the *spec*. 'linear' is no scaling.
  6167. 'dB' returns the values in dB scale, i.e., the dB amplitude
  6168. (20 * log10). 'default' is 'linear'.
  6169. Fc : int, default: 0
  6170. The center frequency of *x*, which offsets the x extents of the
  6171. plot to reflect the frequency range used when a signal is acquired
  6172. and then filtered and downsampled to baseband.
  6173. Returns
  6174. -------
  6175. spectrum : 1-D array
  6176. The values for the magnitude spectrum before scaling (real valued).
  6177. freqs : 1-D array
  6178. The frequencies corresponding to the elements in *spectrum*.
  6179. line : `~matplotlib.lines.Line2D`
  6180. The line created by this function.
  6181. Other Parameters
  6182. ----------------
  6183. data : indexable object, optional
  6184. DATA_PARAMETER_PLACEHOLDER
  6185. **kwargs
  6186. Keyword arguments control the `.Line2D` properties:
  6187. %(Line2D:kwdoc)s
  6188. See Also
  6189. --------
  6190. psd
  6191. Plots the power spectral density.
  6192. angle_spectrum
  6193. Plots the angles of the corresponding frequencies.
  6194. phase_spectrum
  6195. Plots the phase (unwrapped angle) of the corresponding frequencies.
  6196. specgram
  6197. Can plot the magnitude spectrum of segments within the signal in a
  6198. colormap.
  6199. """
  6200. if Fc is None:
  6201. Fc = 0
  6202. spec, freqs = mlab.magnitude_spectrum(x=x, Fs=Fs, window=window,
  6203. pad_to=pad_to, sides=sides)
  6204. freqs += Fc
  6205. yunits = _api.check_getitem(
  6206. {None: 'energy', 'default': 'energy', 'linear': 'energy',
  6207. 'dB': 'dB'},
  6208. scale=scale)
  6209. if yunits == 'energy':
  6210. Z = spec
  6211. else: # yunits == 'dB'
  6212. Z = 20. * np.log10(spec)
  6213. line, = self.plot(freqs, Z, **kwargs)
  6214. self.set_xlabel('Frequency')
  6215. self.set_ylabel('Magnitude (%s)' % yunits)
  6216. return spec, freqs, line
  6217. @_preprocess_data(replace_names=["x"])
  6218. @_docstring.dedent_interpd
  6219. def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
  6220. pad_to=None, sides=None, **kwargs):
  6221. """
  6222. Plot the angle spectrum.
  6223. Compute the angle spectrum (wrapped phase spectrum) of *x*.
  6224. Data is padded to a length of *pad_to* and the windowing function
  6225. *window* is applied to the signal.
  6226. Parameters
  6227. ----------
  6228. x : 1-D array or sequence
  6229. Array or sequence containing the data.
  6230. %(Spectral)s
  6231. %(Single_Spectrum)s
  6232. Fc : int, default: 0
  6233. The center frequency of *x*, which offsets the x extents of the
  6234. plot to reflect the frequency range used when a signal is acquired
  6235. and then filtered and downsampled to baseband.
  6236. Returns
  6237. -------
  6238. spectrum : 1-D array
  6239. The values for the angle spectrum in radians (real valued).
  6240. freqs : 1-D array
  6241. The frequencies corresponding to the elements in *spectrum*.
  6242. line : `~matplotlib.lines.Line2D`
  6243. The line created by this function.
  6244. Other Parameters
  6245. ----------------
  6246. data : indexable object, optional
  6247. DATA_PARAMETER_PLACEHOLDER
  6248. **kwargs
  6249. Keyword arguments control the `.Line2D` properties:
  6250. %(Line2D:kwdoc)s
  6251. See Also
  6252. --------
  6253. magnitude_spectrum
  6254. Plots the magnitudes of the corresponding frequencies.
  6255. phase_spectrum
  6256. Plots the unwrapped version of this function.
  6257. specgram
  6258. Can plot the angle spectrum of segments within the signal in a
  6259. colormap.
  6260. """
  6261. if Fc is None:
  6262. Fc = 0
  6263. spec, freqs = mlab.angle_spectrum(x=x, Fs=Fs, window=window,
  6264. pad_to=pad_to, sides=sides)
  6265. freqs += Fc
  6266. lines = self.plot(freqs, spec, **kwargs)
  6267. self.set_xlabel('Frequency')
  6268. self.set_ylabel('Angle (radians)')
  6269. return spec, freqs, lines[0]
  6270. @_preprocess_data(replace_names=["x"])
  6271. @_docstring.dedent_interpd
  6272. def phase_spectrum(self, x, Fs=None, Fc=None, window=None,
  6273. pad_to=None, sides=None, **kwargs):
  6274. """
  6275. Plot the phase spectrum.
  6276. Compute the phase spectrum (unwrapped angle spectrum) of *x*.
  6277. Data is padded to a length of *pad_to* and the windowing function
  6278. *window* is applied to the signal.
  6279. Parameters
  6280. ----------
  6281. x : 1-D array or sequence
  6282. Array or sequence containing the data
  6283. %(Spectral)s
  6284. %(Single_Spectrum)s
  6285. Fc : int, default: 0
  6286. The center frequency of *x*, which offsets the x extents of the
  6287. plot to reflect the frequency range used when a signal is acquired
  6288. and then filtered and downsampled to baseband.
  6289. Returns
  6290. -------
  6291. spectrum : 1-D array
  6292. The values for the phase spectrum in radians (real valued).
  6293. freqs : 1-D array
  6294. The frequencies corresponding to the elements in *spectrum*.
  6295. line : `~matplotlib.lines.Line2D`
  6296. The line created by this function.
  6297. Other Parameters
  6298. ----------------
  6299. data : indexable object, optional
  6300. DATA_PARAMETER_PLACEHOLDER
  6301. **kwargs
  6302. Keyword arguments control the `.Line2D` properties:
  6303. %(Line2D:kwdoc)s
  6304. See Also
  6305. --------
  6306. magnitude_spectrum
  6307. Plots the magnitudes of the corresponding frequencies.
  6308. angle_spectrum
  6309. Plots the wrapped version of this function.
  6310. specgram
  6311. Can plot the phase spectrum of segments within the signal in a
  6312. colormap.
  6313. """
  6314. if Fc is None:
  6315. Fc = 0
  6316. spec, freqs = mlab.phase_spectrum(x=x, Fs=Fs, window=window,
  6317. pad_to=pad_to, sides=sides)
  6318. freqs += Fc
  6319. lines = self.plot(freqs, spec, **kwargs)
  6320. self.set_xlabel('Frequency')
  6321. self.set_ylabel('Phase (radians)')
  6322. return spec, freqs, lines[0]
  6323. @_preprocess_data(replace_names=["x", "y"])
  6324. @_docstring.dedent_interpd
  6325. def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
  6326. window=mlab.window_hanning, noverlap=0, pad_to=None,
  6327. sides='default', scale_by_freq=None, **kwargs):
  6328. r"""
  6329. Plot the coherence between *x* and *y*.
  6330. Coherence is the normalized cross spectral density:
  6331. .. math::
  6332. C_{xy} = \frac{|P_{xy}|^2}{P_{xx}P_{yy}}
  6333. Parameters
  6334. ----------
  6335. %(Spectral)s
  6336. %(PSD)s
  6337. noverlap : int, default: 0 (no overlap)
  6338. The number of points of overlap between blocks.
  6339. Fc : int, default: 0
  6340. The center frequency of *x*, which offsets the x extents of the
  6341. plot to reflect the frequency range used when a signal is acquired
  6342. and then filtered and downsampled to baseband.
  6343. Returns
  6344. -------
  6345. Cxy : 1-D array
  6346. The coherence vector.
  6347. freqs : 1-D array
  6348. The frequencies for the elements in *Cxy*.
  6349. Other Parameters
  6350. ----------------
  6351. data : indexable object, optional
  6352. DATA_PARAMETER_PLACEHOLDER
  6353. **kwargs
  6354. Keyword arguments control the `.Line2D` properties:
  6355. %(Line2D:kwdoc)s
  6356. References
  6357. ----------
  6358. Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,
  6359. John Wiley & Sons (1986)
  6360. """
  6361. cxy, freqs = mlab.cohere(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend,
  6362. window=window, noverlap=noverlap,
  6363. scale_by_freq=scale_by_freq, sides=sides,
  6364. pad_to=pad_to)
  6365. freqs += Fc
  6366. self.plot(freqs, cxy, **kwargs)
  6367. self.set_xlabel('Frequency')
  6368. self.set_ylabel('Coherence')
  6369. self.grid(True)
  6370. return cxy, freqs
  6371. @_preprocess_data(replace_names=["x"])
  6372. @_docstring.dedent_interpd
  6373. def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
  6374. window=None, noverlap=None,
  6375. cmap=None, xextent=None, pad_to=None, sides=None,
  6376. scale_by_freq=None, mode=None, scale=None,
  6377. vmin=None, vmax=None, **kwargs):
  6378. """
  6379. Plot a spectrogram.
  6380. Compute and plot a spectrogram of data in *x*. Data are split into
  6381. *NFFT* length segments and the spectrum of each section is
  6382. computed. The windowing function *window* is applied to each
  6383. segment, and the amount of overlap of each segment is
  6384. specified with *noverlap*. The spectrogram is plotted as a colormap
  6385. (using imshow).
  6386. Parameters
  6387. ----------
  6388. x : 1-D array or sequence
  6389. Array or sequence containing the data.
  6390. %(Spectral)s
  6391. %(PSD)s
  6392. mode : {'default', 'psd', 'magnitude', 'angle', 'phase'}
  6393. What sort of spectrum to use. Default is 'psd', which takes the
  6394. power spectral density. 'magnitude' returns the magnitude
  6395. spectrum. 'angle' returns the phase spectrum without unwrapping.
  6396. 'phase' returns the phase spectrum with unwrapping.
  6397. noverlap : int, default: 128
  6398. The number of points of overlap between blocks.
  6399. scale : {'default', 'linear', 'dB'}
  6400. The scaling of the values in the *spec*. 'linear' is no scaling.
  6401. 'dB' returns the values in dB scale. When *mode* is 'psd',
  6402. this is dB power (10 * log10). Otherwise, this is dB amplitude
  6403. (20 * log10). 'default' is 'dB' if *mode* is 'psd' or
  6404. 'magnitude' and 'linear' otherwise. This must be 'linear'
  6405. if *mode* is 'angle' or 'phase'.
  6406. Fc : int, default: 0
  6407. The center frequency of *x*, which offsets the x extents of the
  6408. plot to reflect the frequency range used when a signal is acquired
  6409. and then filtered and downsampled to baseband.
  6410. cmap : `.Colormap`, default: :rc:`image.cmap`
  6411. xextent : *None* or (xmin, xmax)
  6412. The image extent along the x-axis. The default sets *xmin* to the
  6413. left border of the first bin (*spectrum* column) and *xmax* to the
  6414. right border of the last bin. Note that for *noverlap>0* the width
  6415. of the bins is smaller than those of the segments.
  6416. data : indexable object, optional
  6417. DATA_PARAMETER_PLACEHOLDER
  6418. **kwargs
  6419. Additional keyword arguments are passed on to `~.axes.Axes.imshow`
  6420. which makes the specgram image. The origin keyword argument
  6421. is not supported.
  6422. Returns
  6423. -------
  6424. spectrum : 2D array
  6425. Columns are the periodograms of successive segments.
  6426. freqs : 1-D array
  6427. The frequencies corresponding to the rows in *spectrum*.
  6428. t : 1-D array
  6429. The times corresponding to midpoints of segments (i.e., the columns
  6430. in *spectrum*).
  6431. im : `.AxesImage`
  6432. The image created by imshow containing the spectrogram.
  6433. See Also
  6434. --------
  6435. psd
  6436. Differs in the default overlap; in returning the mean of the
  6437. segment periodograms; in not returning times; and in generating a
  6438. line plot instead of colormap.
  6439. magnitude_spectrum
  6440. A single spectrum, similar to having a single segment when *mode*
  6441. is 'magnitude'. Plots a line instead of a colormap.
  6442. angle_spectrum
  6443. A single spectrum, similar to having a single segment when *mode*
  6444. is 'angle'. Plots a line instead of a colormap.
  6445. phase_spectrum
  6446. A single spectrum, similar to having a single segment when *mode*
  6447. is 'phase'. Plots a line instead of a colormap.
  6448. Notes
  6449. -----
  6450. The parameters *detrend* and *scale_by_freq* do only apply when *mode*
  6451. is set to 'psd'.
  6452. """
  6453. if NFFT is None:
  6454. NFFT = 256 # same default as in mlab.specgram()
  6455. if Fc is None:
  6456. Fc = 0 # same default as in mlab._spectral_helper()
  6457. if noverlap is None:
  6458. noverlap = 128 # same default as in mlab.specgram()
  6459. if Fs is None:
  6460. Fs = 2 # same default as in mlab._spectral_helper()
  6461. if mode == 'complex':
  6462. raise ValueError('Cannot plot a complex specgram')
  6463. if scale is None or scale == 'default':
  6464. if mode in ['angle', 'phase']:
  6465. scale = 'linear'
  6466. else:
  6467. scale = 'dB'
  6468. elif mode in ['angle', 'phase'] and scale == 'dB':
  6469. raise ValueError('Cannot use dB scale with angle or phase mode')
  6470. spec, freqs, t = mlab.specgram(x=x, NFFT=NFFT, Fs=Fs,
  6471. detrend=detrend, window=window,
  6472. noverlap=noverlap, pad_to=pad_to,
  6473. sides=sides,
  6474. scale_by_freq=scale_by_freq,
  6475. mode=mode)
  6476. if scale == 'linear':
  6477. Z = spec
  6478. elif scale == 'dB':
  6479. if mode is None or mode == 'default' or mode == 'psd':
  6480. Z = 10. * np.log10(spec)
  6481. else:
  6482. Z = 20. * np.log10(spec)
  6483. else:
  6484. raise ValueError(f'Unknown scale {scale!r}')
  6485. Z = np.flipud(Z)
  6486. if xextent is None:
  6487. # padding is needed for first and last segment:
  6488. pad_xextent = (NFFT-noverlap) / Fs / 2
  6489. xextent = np.min(t) - pad_xextent, np.max(t) + pad_xextent
  6490. xmin, xmax = xextent
  6491. freqs += Fc
  6492. extent = xmin, xmax, freqs[0], freqs[-1]
  6493. if 'origin' in kwargs:
  6494. raise _api.kwarg_error("specgram", "origin")
  6495. im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax,
  6496. origin='upper', **kwargs)
  6497. self.axis('auto')
  6498. return spec, freqs, t, im
  6499. @_docstring.dedent_interpd
  6500. def spy(self, Z, precision=0, marker=None, markersize=None,
  6501. aspect='equal', origin="upper", **kwargs):
  6502. """
  6503. Plot the sparsity pattern of a 2D array.
  6504. This visualizes the non-zero values of the array.
  6505. Two plotting styles are available: image and marker. Both
  6506. are available for full arrays, but only the marker style
  6507. works for `scipy.sparse.spmatrix` instances.
  6508. **Image style**
  6509. If *marker* and *markersize* are *None*, `~.Axes.imshow` is used. Any
  6510. extra remaining keyword arguments are passed to this method.
  6511. **Marker style**
  6512. If *Z* is a `scipy.sparse.spmatrix` or *marker* or *markersize* are
  6513. *None*, a `.Line2D` object will be returned with the value of marker
  6514. determining the marker type, and any remaining keyword arguments
  6515. passed to `~.Axes.plot`.
  6516. Parameters
  6517. ----------
  6518. Z : (M, N) array-like
  6519. The array to be plotted.
  6520. precision : float or 'present', default: 0
  6521. If *precision* is 0, any non-zero value will be plotted. Otherwise,
  6522. values of :math:`|Z| > precision` will be plotted.
  6523. For `scipy.sparse.spmatrix` instances, you can also
  6524. pass 'present'. In this case any value present in the array
  6525. will be plotted, even if it is identically zero.
  6526. aspect : {'equal', 'auto', None} or float, default: 'equal'
  6527. The aspect ratio of the Axes. This parameter is particularly
  6528. relevant for images since it determines whether data pixels are
  6529. square.
  6530. This parameter is a shortcut for explicitly calling
  6531. `.Axes.set_aspect`. See there for further details.
  6532. - 'equal': Ensures an aspect ratio of 1. Pixels will be square.
  6533. - 'auto': The Axes is kept fixed and the aspect is adjusted so
  6534. that the data fit in the Axes. In general, this will result in
  6535. non-square pixels.
  6536. - *None*: Use :rc:`image.aspect`.
  6537. origin : {'upper', 'lower'}, default: :rc:`image.origin`
  6538. Place the [0, 0] index of the array in the upper left or lower left
  6539. corner of the Axes. The convention 'upper' is typically used for
  6540. matrices and images.
  6541. Returns
  6542. -------
  6543. `~matplotlib.image.AxesImage` or `.Line2D`
  6544. The return type depends on the plotting style (see above).
  6545. Other Parameters
  6546. ----------------
  6547. **kwargs
  6548. The supported additional parameters depend on the plotting style.
  6549. For the image style, you can pass the following additional
  6550. parameters of `~.Axes.imshow`:
  6551. - *cmap*
  6552. - *alpha*
  6553. - *url*
  6554. - any `.Artist` properties (passed on to the `.AxesImage`)
  6555. For the marker style, you can pass any `.Line2D` property except
  6556. for *linestyle*:
  6557. %(Line2D:kwdoc)s
  6558. """
  6559. if marker is None and markersize is None and hasattr(Z, 'tocoo'):
  6560. marker = 's'
  6561. _api.check_in_list(["upper", "lower"], origin=origin)
  6562. if marker is None and markersize is None:
  6563. Z = np.asarray(Z)
  6564. mask = np.abs(Z) > precision
  6565. if 'cmap' not in kwargs:
  6566. kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'],
  6567. name='binary')
  6568. if 'interpolation' in kwargs:
  6569. raise _api.kwarg_error("spy", "interpolation")
  6570. if 'norm' not in kwargs:
  6571. kwargs['norm'] = mcolors.NoNorm()
  6572. ret = self.imshow(mask, interpolation='nearest',
  6573. aspect=aspect, origin=origin,
  6574. **kwargs)
  6575. else:
  6576. if hasattr(Z, 'tocoo'):
  6577. c = Z.tocoo()
  6578. if precision == 'present':
  6579. y = c.row
  6580. x = c.col
  6581. else:
  6582. nonzero = np.abs(c.data) > precision
  6583. y = c.row[nonzero]
  6584. x = c.col[nonzero]
  6585. else:
  6586. Z = np.asarray(Z)
  6587. nonzero = np.abs(Z) > precision
  6588. y, x = np.nonzero(nonzero)
  6589. if marker is None:
  6590. marker = 's'
  6591. if markersize is None:
  6592. markersize = 10
  6593. if 'linestyle' in kwargs:
  6594. raise _api.kwarg_error("spy", "linestyle")
  6595. ret = mlines.Line2D(
  6596. x, y, linestyle='None', marker=marker, markersize=markersize,
  6597. **kwargs)
  6598. self.add_line(ret)
  6599. nr, nc = Z.shape
  6600. self.set_xlim(-0.5, nc - 0.5)
  6601. if origin == "upper":
  6602. self.set_ylim(nr - 0.5, -0.5)
  6603. else:
  6604. self.set_ylim(-0.5, nr - 0.5)
  6605. self.set_aspect(aspect)
  6606. self.title.set_y(1.05)
  6607. if origin == "upper":
  6608. self.xaxis.tick_top()
  6609. else: # lower
  6610. self.xaxis.tick_bottom()
  6611. self.xaxis.set_ticks_position('both')
  6612. self.xaxis.set_major_locator(
  6613. mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
  6614. self.yaxis.set_major_locator(
  6615. mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
  6616. return ret
  6617. def matshow(self, Z, **kwargs):
  6618. """
  6619. Plot the values of a 2D matrix or array as color-coded image.
  6620. The matrix will be shown the way it would be printed, with the first
  6621. row at the top. Row and column numbering is zero-based.
  6622. Parameters
  6623. ----------
  6624. Z : (M, N) array-like
  6625. The matrix to be displayed.
  6626. Returns
  6627. -------
  6628. `~matplotlib.image.AxesImage`
  6629. Other Parameters
  6630. ----------------
  6631. **kwargs : `~matplotlib.axes.Axes.imshow` arguments
  6632. See Also
  6633. --------
  6634. imshow : More general function to plot data on a 2D regular raster.
  6635. Notes
  6636. -----
  6637. This is just a convenience function wrapping `.imshow` to set useful
  6638. defaults for displaying a matrix. In particular:
  6639. - Set ``origin='upper'``.
  6640. - Set ``interpolation='nearest'``.
  6641. - Set ``aspect='equal'``.
  6642. - Ticks are placed to the left and above.
  6643. - Ticks are formatted to show integer indices.
  6644. """
  6645. Z = np.asanyarray(Z)
  6646. kw = {'origin': 'upper',
  6647. 'interpolation': 'nearest',
  6648. 'aspect': 'equal', # (already the imshow default)
  6649. **kwargs}
  6650. im = self.imshow(Z, **kw)
  6651. self.title.set_y(1.05)
  6652. self.xaxis.tick_top()
  6653. self.xaxis.set_ticks_position('both')
  6654. self.xaxis.set_major_locator(
  6655. mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
  6656. self.yaxis.set_major_locator(
  6657. mticker.MaxNLocator(nbins=9, steps=[1, 2, 5, 10], integer=True))
  6658. return im
  6659. @_preprocess_data(replace_names=["dataset"])
  6660. def violinplot(self, dataset, positions=None, vert=True, widths=0.5,
  6661. showmeans=False, showextrema=True, showmedians=False,
  6662. quantiles=None, points=100, bw_method=None):
  6663. """
  6664. Make a violin plot.
  6665. Make a violin plot for each column of *dataset* or each vector in
  6666. sequence *dataset*. Each filled area extends to represent the
  6667. entire data range, with optional lines at the mean, the median,
  6668. the minimum, the maximum, and user-specified quantiles.
  6669. Parameters
  6670. ----------
  6671. dataset : Array or a sequence of vectors.
  6672. The input data.
  6673. positions : array-like, default: [1, 2, ..., n]
  6674. The positions of the violins. The ticks and limits are
  6675. automatically set to match the positions.
  6676. vert : bool, default: True.
  6677. If true, creates a vertical violin plot.
  6678. Otherwise, creates a horizontal violin plot.
  6679. widths : array-like, default: 0.5
  6680. Either a scalar or a vector that sets the maximal width of
  6681. each violin. The default is 0.5, which uses about half of the
  6682. available horizontal space.
  6683. showmeans : bool, default: False
  6684. If `True`, will toggle rendering of the means.
  6685. showextrema : bool, default: True
  6686. If `True`, will toggle rendering of the extrema.
  6687. showmedians : bool, default: False
  6688. If `True`, will toggle rendering of the medians.
  6689. quantiles : array-like, default: None
  6690. If not None, set a list of floats in interval [0, 1] for each violin,
  6691. which stands for the quantiles that will be rendered for that
  6692. violin.
  6693. points : int, default: 100
  6694. Defines the number of points to evaluate each of the
  6695. gaussian kernel density estimations at.
  6696. bw_method : str, scalar or callable, optional
  6697. The method used to calculate the estimator bandwidth. This can be
  6698. 'scott', 'silverman', a scalar constant or a callable. If a
  6699. scalar, this will be used directly as `kde.factor`. If a
  6700. callable, it should take a `matplotlib.mlab.GaussianKDE` instance as
  6701. its only parameter and return a scalar. If None (default), 'scott'
  6702. is used.
  6703. data : indexable object, optional
  6704. DATA_PARAMETER_PLACEHOLDER
  6705. Returns
  6706. -------
  6707. dict
  6708. A dictionary mapping each component of the violinplot to a
  6709. list of the corresponding collection instances created. The
  6710. dictionary has the following keys:
  6711. - ``bodies``: A list of the `~.collections.PolyCollection`
  6712. instances containing the filled area of each violin.
  6713. - ``cmeans``: A `~.collections.LineCollection` instance that marks
  6714. the mean values of each of the violin's distribution.
  6715. - ``cmins``: A `~.collections.LineCollection` instance that marks
  6716. the bottom of each violin's distribution.
  6717. - ``cmaxes``: A `~.collections.LineCollection` instance that marks
  6718. the top of each violin's distribution.
  6719. - ``cbars``: A `~.collections.LineCollection` instance that marks
  6720. the centers of each violin's distribution.
  6721. - ``cmedians``: A `~.collections.LineCollection` instance that
  6722. marks the median values of each of the violin's distribution.
  6723. - ``cquantiles``: A `~.collections.LineCollection` instance created
  6724. to identify the quantile values of each of the violin's
  6725. distribution.
  6726. """
  6727. def _kde_method(X, coords):
  6728. # Unpack in case of e.g. Pandas or xarray object
  6729. X = cbook._unpack_to_numpy(X)
  6730. # fallback gracefully if the vector contains only one value
  6731. if np.all(X[0] == X):
  6732. return (X[0] == coords).astype(float)
  6733. kde = mlab.GaussianKDE(X, bw_method)
  6734. return kde.evaluate(coords)
  6735. vpstats = cbook.violin_stats(dataset, _kde_method, points=points,
  6736. quantiles=quantiles)
  6737. return self.violin(vpstats, positions=positions, vert=vert,
  6738. widths=widths, showmeans=showmeans,
  6739. showextrema=showextrema, showmedians=showmedians)
  6740. def violin(self, vpstats, positions=None, vert=True, widths=0.5,
  6741. showmeans=False, showextrema=True, showmedians=False):
  6742. """
  6743. Drawing function for violin plots.
  6744. Draw a violin plot for each column of *vpstats*. Each filled area
  6745. extends to represent the entire data range, with optional lines at the
  6746. mean, the median, the minimum, the maximum, and the quantiles values.
  6747. Parameters
  6748. ----------
  6749. vpstats : list of dicts
  6750. A list of dictionaries containing stats for each violin plot.
  6751. Required keys are:
  6752. - ``coords``: A list of scalars containing the coordinates that
  6753. the violin's kernel density estimate were evaluated at.
  6754. - ``vals``: A list of scalars containing the values of the
  6755. kernel density estimate at each of the coordinates given
  6756. in *coords*.
  6757. - ``mean``: The mean value for this violin's dataset.
  6758. - ``median``: The median value for this violin's dataset.
  6759. - ``min``: The minimum value for this violin's dataset.
  6760. - ``max``: The maximum value for this violin's dataset.
  6761. Optional keys are:
  6762. - ``quantiles``: A list of scalars containing the quantile values
  6763. for this violin's dataset.
  6764. positions : array-like, default: [1, 2, ..., n]
  6765. The positions of the violins. The ticks and limits are
  6766. automatically set to match the positions.
  6767. vert : bool, default: True.
  6768. If true, plots the violins vertically.
  6769. Otherwise, plots the violins horizontally.
  6770. widths : array-like, default: 0.5
  6771. Either a scalar or a vector that sets the maximal width of
  6772. each violin. The default is 0.5, which uses about half of the
  6773. available horizontal space.
  6774. showmeans : bool, default: False
  6775. If true, will toggle rendering of the means.
  6776. showextrema : bool, default: True
  6777. If true, will toggle rendering of the extrema.
  6778. showmedians : bool, default: False
  6779. If true, will toggle rendering of the medians.
  6780. Returns
  6781. -------
  6782. dict
  6783. A dictionary mapping each component of the violinplot to a
  6784. list of the corresponding collection instances created. The
  6785. dictionary has the following keys:
  6786. - ``bodies``: A list of the `~.collections.PolyCollection`
  6787. instances containing the filled area of each violin.
  6788. - ``cmeans``: A `~.collections.LineCollection` instance that marks
  6789. the mean values of each of the violin's distribution.
  6790. - ``cmins``: A `~.collections.LineCollection` instance that marks
  6791. the bottom of each violin's distribution.
  6792. - ``cmaxes``: A `~.collections.LineCollection` instance that marks
  6793. the top of each violin's distribution.
  6794. - ``cbars``: A `~.collections.LineCollection` instance that marks
  6795. the centers of each violin's distribution.
  6796. - ``cmedians``: A `~.collections.LineCollection` instance that
  6797. marks the median values of each of the violin's distribution.
  6798. - ``cquantiles``: A `~.collections.LineCollection` instance created
  6799. to identify the quantiles values of each of the violin's
  6800. distribution.
  6801. """
  6802. # Statistical quantities to be plotted on the violins
  6803. means = []
  6804. mins = []
  6805. maxes = []
  6806. medians = []
  6807. quantiles = []
  6808. qlens = [] # Number of quantiles in each dataset.
  6809. artists = {} # Collections to be returned
  6810. N = len(vpstats)
  6811. datashape_message = ("List of violinplot statistics and `{0}` "
  6812. "values must have the same length")
  6813. # Validate positions
  6814. if positions is None:
  6815. positions = range(1, N + 1)
  6816. elif len(positions) != N:
  6817. raise ValueError(datashape_message.format("positions"))
  6818. # Validate widths
  6819. if np.isscalar(widths):
  6820. widths = [widths] * N
  6821. elif len(widths) != N:
  6822. raise ValueError(datashape_message.format("widths"))
  6823. # Calculate ranges for statistics lines (shape (2, N)).
  6824. line_ends = [[-0.25], [0.25]] * np.array(widths) + positions
  6825. # Colors.
  6826. if mpl.rcParams['_internal.classic_mode']:
  6827. fillcolor = 'y'
  6828. linecolor = 'r'
  6829. else:
  6830. fillcolor = linecolor = self._get_lines.get_next_color()
  6831. # Check whether we are rendering vertically or horizontally
  6832. if vert:
  6833. fill = self.fill_betweenx
  6834. perp_lines = functools.partial(self.hlines, colors=linecolor)
  6835. par_lines = functools.partial(self.vlines, colors=linecolor)
  6836. else:
  6837. fill = self.fill_between
  6838. perp_lines = functools.partial(self.vlines, colors=linecolor)
  6839. par_lines = functools.partial(self.hlines, colors=linecolor)
  6840. # Render violins
  6841. bodies = []
  6842. for stats, pos, width in zip(vpstats, positions, widths):
  6843. # The 0.5 factor reflects the fact that we plot from v-p to v+p.
  6844. vals = np.array(stats['vals'])
  6845. vals = 0.5 * width * vals / vals.max()
  6846. bodies += [fill(stats['coords'], -vals + pos, vals + pos,
  6847. facecolor=fillcolor, alpha=0.3)]
  6848. means.append(stats['mean'])
  6849. mins.append(stats['min'])
  6850. maxes.append(stats['max'])
  6851. medians.append(stats['median'])
  6852. q = stats.get('quantiles') # a list of floats, or None
  6853. if q is None:
  6854. q = []
  6855. quantiles.extend(q)
  6856. qlens.append(len(q))
  6857. artists['bodies'] = bodies
  6858. if showmeans: # Render means
  6859. artists['cmeans'] = perp_lines(means, *line_ends)
  6860. if showextrema: # Render extrema
  6861. artists['cmaxes'] = perp_lines(maxes, *line_ends)
  6862. artists['cmins'] = perp_lines(mins, *line_ends)
  6863. artists['cbars'] = par_lines(positions, mins, maxes)
  6864. if showmedians: # Render medians
  6865. artists['cmedians'] = perp_lines(medians, *line_ends)
  6866. if quantiles: # Render quantiles: each width is repeated qlen times.
  6867. artists['cquantiles'] = perp_lines(
  6868. quantiles, *np.repeat(line_ends, qlens, axis=1))
  6869. return artists
  6870. # Methods that are entirely implemented in other modules.
  6871. table = mtable.table
  6872. # args can be either Y or y1, y2, ... and all should be replaced
  6873. stackplot = _preprocess_data()(mstack.stackplot)
  6874. streamplot = _preprocess_data(
  6875. replace_names=["x", "y", "u", "v", "start_points"])(mstream.streamplot)
  6876. tricontour = mtri.tricontour
  6877. tricontourf = mtri.tricontourf
  6878. tripcolor = mtri.tripcolor
  6879. triplot = mtri.triplot
  6880. def _get_aspect_ratio(self):
  6881. """
  6882. Convenience method to calculate the aspect ratio of the axes in
  6883. the display coordinate system.
  6884. """
  6885. figure_size = self.get_figure().get_size_inches()
  6886. ll, ur = self.get_position() * figure_size
  6887. width, height = ur - ll
  6888. return height / (width * self.get_data_ratio())