test_axes.py 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466
  1. from collections import namedtuple
  2. import datetime
  3. from decimal import Decimal
  4. import io
  5. from itertools import product
  6. import platform
  7. from types import SimpleNamespace
  8. try:
  9. from contextlib import nullcontext
  10. except ImportError:
  11. from contextlib import ExitStack as nullcontext # Py3.6.
  12. import dateutil.tz
  13. import numpy as np
  14. from numpy import ma
  15. from cycler import cycler
  16. import pytest
  17. import matplotlib
  18. import matplotlib as mpl
  19. from matplotlib.testing.decorators import (
  20. image_comparison, check_figures_equal, remove_ticks_and_titles)
  21. import matplotlib.colors as mcolors
  22. import matplotlib.dates as mdates
  23. import matplotlib.font_manager as mfont_manager
  24. import matplotlib.markers as mmarkers
  25. import matplotlib.patches as mpatches
  26. import matplotlib.pyplot as plt
  27. import matplotlib.ticker as mticker
  28. import matplotlib.transforms as mtransforms
  29. from numpy.testing import (
  30. assert_allclose, assert_array_equal, assert_array_almost_equal)
  31. from matplotlib import rc_context
  32. from matplotlib.cbook import MatplotlibDeprecationWarning
  33. # Note: Some test cases are run twice: once normally and once with labeled data
  34. # These two must be defined in the same test function or need to have
  35. # different baseline images to prevent race conditions when pytest runs
  36. # the tests with multiple threads.
  37. def test_get_labels():
  38. fig, ax = plt.subplots()
  39. ax.set_xlabel('x label')
  40. ax.set_ylabel('y label')
  41. assert ax.get_xlabel() == 'x label'
  42. assert ax.get_ylabel() == 'y label'
  43. @check_figures_equal()
  44. def test_label_loc_vertical(fig_test, fig_ref):
  45. ax = fig_test.subplots()
  46. sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
  47. ax.set_ylabel('Y Label', loc='top')
  48. ax.set_xlabel('X Label', loc='right')
  49. cbar = fig_test.colorbar(sc)
  50. cbar.set_label("Z Label", loc='top')
  51. ax = fig_ref.subplots()
  52. sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
  53. ax.set_ylabel('Y Label', y=1, ha='right')
  54. ax.set_xlabel('X Label', x=1, ha='right')
  55. cbar = fig_ref.colorbar(sc)
  56. cbar.set_label("Z Label", y=1, ha='right')
  57. @check_figures_equal()
  58. def test_label_loc_horizontal(fig_test, fig_ref):
  59. ax = fig_test.subplots()
  60. sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
  61. ax.set_ylabel('Y Label', loc='bottom')
  62. ax.set_xlabel('X Label', loc='left')
  63. cbar = fig_test.colorbar(sc, orientation='horizontal')
  64. cbar.set_label("Z Label", loc='left')
  65. ax = fig_ref.subplots()
  66. sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
  67. ax.set_ylabel('Y Label', y=0, ha='left')
  68. ax.set_xlabel('X Label', x=0, ha='left')
  69. cbar = fig_ref.colorbar(sc, orientation='horizontal')
  70. cbar.set_label("Z Label", x=0, ha='left')
  71. @check_figures_equal()
  72. def test_label_loc_rc(fig_test, fig_ref):
  73. with matplotlib.rc_context({"xaxis.labellocation": "right",
  74. "yaxis.labellocation": "top"}):
  75. ax = fig_test.subplots()
  76. sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
  77. ax.set_ylabel('Y Label')
  78. ax.set_xlabel('X Label')
  79. cbar = fig_test.colorbar(sc, orientation='horizontal')
  80. cbar.set_label("Z Label")
  81. ax = fig_ref.subplots()
  82. sc = ax.scatter([1, 2], [1, 2], c=[1, 2])
  83. ax.set_ylabel('Y Label', y=1, ha='right')
  84. ax.set_xlabel('X Label', x=1, ha='right')
  85. cbar = fig_ref.colorbar(sc, orientation='horizontal')
  86. cbar.set_label("Z Label", x=1, ha='right')
  87. @check_figures_equal(extensions=["png"])
  88. def test_acorr(fig_test, fig_ref):
  89. np.random.seed(19680801)
  90. Nx = 512
  91. x = np.random.normal(0, 1, Nx).cumsum()
  92. maxlags = Nx-1
  93. fig_test, ax_test = plt.subplots()
  94. ax_test.acorr(x, maxlags=maxlags)
  95. fig_ref, ax_ref = plt.subplots()
  96. # Normalized autocorrelation
  97. norm_auto_corr = np.correlate(x, x, mode="full")/np.dot(x, x)
  98. lags = np.arange(-maxlags, maxlags+1)
  99. norm_auto_corr = norm_auto_corr[Nx-1-maxlags:Nx+maxlags]
  100. ax_ref.vlines(lags, [0], norm_auto_corr)
  101. ax_ref.axhline(y=0, xmin=0, xmax=1)
  102. @check_figures_equal(extensions=["png"])
  103. def test_spy(fig_test, fig_ref):
  104. np.random.seed(19680801)
  105. a = np.ones(32 * 32)
  106. a[:16 * 32] = 0
  107. np.random.shuffle(a)
  108. a = a.reshape((32, 32))
  109. axs_test = fig_test.subplots(2)
  110. axs_test[0].spy(a)
  111. axs_test[1].spy(a, marker=".", origin="lower")
  112. axs_ref = fig_ref.subplots(2)
  113. axs_ref[0].imshow(a, cmap="gray_r", interpolation="nearest")
  114. axs_ref[0].xaxis.tick_top()
  115. axs_ref[1].plot(*np.nonzero(a)[::-1], ".", markersize=10)
  116. axs_ref[1].set(
  117. aspect=1, xlim=axs_ref[0].get_xlim(), ylim=axs_ref[0].get_ylim()[::-1])
  118. for ax in axs_ref:
  119. ax.xaxis.set_ticks_position("both")
  120. def test_spy_invalid_kwargs():
  121. fig, ax = plt.subplots()
  122. for unsupported_kw in [{'interpolation': 'nearest'},
  123. {'marker': 'o', 'linestyle': 'solid'}]:
  124. with pytest.raises(TypeError):
  125. ax.spy(np.eye(3, 3), **unsupported_kw)
  126. @check_figures_equal(extensions=["png"])
  127. def test_matshow(fig_test, fig_ref):
  128. mpl.style.use("mpl20")
  129. a = np.random.rand(32, 32)
  130. fig_test.add_subplot().matshow(a)
  131. ax_ref = fig_ref.add_subplot()
  132. ax_ref.imshow(a)
  133. ax_ref.xaxis.tick_top()
  134. ax_ref.xaxis.set_ticks_position('both')
  135. @image_comparison(['formatter_ticker_001',
  136. 'formatter_ticker_002',
  137. 'formatter_ticker_003',
  138. 'formatter_ticker_004',
  139. 'formatter_ticker_005',
  140. ])
  141. def test_formatter_ticker():
  142. import matplotlib.testing.jpl_units as units
  143. units.register()
  144. # This should affect the tick size. (Tests issue #543)
  145. matplotlib.rcParams['lines.markeredgewidth'] = 30
  146. # This essentially test to see if user specified labels get overwritten
  147. # by the auto labeler functionality of the axes.
  148. xdata = [x*units.sec for x in range(10)]
  149. ydata1 = [(1.5*y - 0.5)*units.km for y in range(10)]
  150. ydata2 = [(1.75*y - 1.0)*units.km for y in range(10)]
  151. ax = plt.figure().subplots()
  152. ax.set_xlabel("x-label 001")
  153. ax = plt.figure().subplots()
  154. ax.set_xlabel("x-label 001")
  155. ax.plot(xdata, ydata1, color='blue', xunits="sec")
  156. ax = plt.figure().subplots()
  157. ax.set_xlabel("x-label 001")
  158. ax.plot(xdata, ydata1, color='blue', xunits="sec")
  159. ax.set_xlabel("x-label 003")
  160. ax = plt.figure().subplots()
  161. ax.plot(xdata, ydata1, color='blue', xunits="sec")
  162. ax.plot(xdata, ydata2, color='green', xunits="hour")
  163. ax.set_xlabel("x-label 004")
  164. # See SF bug 2846058
  165. # https://sourceforge.net/tracker/?func=detail&aid=2846058&group_id=80706&atid=560720
  166. ax = plt.figure().subplots()
  167. ax.plot(xdata, ydata1, color='blue', xunits="sec")
  168. ax.plot(xdata, ydata2, color='green', xunits="hour")
  169. ax.set_xlabel("x-label 005")
  170. ax.autoscale_view()
  171. def test_funcformatter_auto_formatter():
  172. def _formfunc(x, pos):
  173. return ''
  174. ax = plt.figure().subplots()
  175. assert ax.xaxis.isDefault_majfmt
  176. assert ax.xaxis.isDefault_minfmt
  177. assert ax.yaxis.isDefault_majfmt
  178. assert ax.yaxis.isDefault_minfmt
  179. ax.xaxis.set_major_formatter(_formfunc)
  180. assert not ax.xaxis.isDefault_majfmt
  181. assert ax.xaxis.isDefault_minfmt
  182. assert ax.yaxis.isDefault_majfmt
  183. assert ax.yaxis.isDefault_minfmt
  184. targ_funcformatter = mticker.FuncFormatter(_formfunc)
  185. assert isinstance(ax.xaxis.get_major_formatter(),
  186. mticker.FuncFormatter)
  187. assert ax.xaxis.get_major_formatter().func == targ_funcformatter.func
  188. def test_strmethodformatter_auto_formatter():
  189. formstr = '{x}_{pos}'
  190. ax = plt.figure().subplots()
  191. assert ax.xaxis.isDefault_majfmt
  192. assert ax.xaxis.isDefault_minfmt
  193. assert ax.yaxis.isDefault_majfmt
  194. assert ax.yaxis.isDefault_minfmt
  195. ax.yaxis.set_minor_formatter(formstr)
  196. assert ax.xaxis.isDefault_majfmt
  197. assert ax.xaxis.isDefault_minfmt
  198. assert ax.yaxis.isDefault_majfmt
  199. assert not ax.yaxis.isDefault_minfmt
  200. targ_strformatter = mticker.StrMethodFormatter(formstr)
  201. assert isinstance(ax.yaxis.get_minor_formatter(),
  202. mticker.StrMethodFormatter)
  203. assert ax.yaxis.get_minor_formatter().fmt == targ_strformatter.fmt
  204. @image_comparison(["twin_axis_locators_formatters"])
  205. def test_twin_axis_locators_formatters():
  206. vals = np.linspace(0, 1, num=5, endpoint=True)
  207. locs = np.sin(np.pi * vals / 2.0)
  208. majl = plt.FixedLocator(locs)
  209. minl = plt.FixedLocator([0.1, 0.2, 0.3])
  210. fig = plt.figure()
  211. ax1 = fig.add_subplot(1, 1, 1)
  212. ax1.plot([0.1, 100], [0, 1])
  213. ax1.yaxis.set_major_locator(majl)
  214. ax1.yaxis.set_minor_locator(minl)
  215. ax1.yaxis.set_major_formatter(plt.FormatStrFormatter('%08.2lf'))
  216. ax1.yaxis.set_minor_formatter(plt.FixedFormatter(['tricks', 'mind',
  217. 'jedi']))
  218. ax1.xaxis.set_major_locator(plt.LinearLocator())
  219. ax1.xaxis.set_minor_locator(plt.FixedLocator([15, 35, 55, 75]))
  220. ax1.xaxis.set_major_formatter(plt.FormatStrFormatter('%05.2lf'))
  221. ax1.xaxis.set_minor_formatter(plt.FixedFormatter(['c', '3', 'p', 'o']))
  222. ax1.twiny()
  223. ax1.twinx()
  224. def test_twinx_cla():
  225. fig, ax = plt.subplots()
  226. ax2 = ax.twinx()
  227. ax3 = ax2.twiny()
  228. plt.draw()
  229. assert not ax2.xaxis.get_visible()
  230. assert not ax2.patch.get_visible()
  231. ax2.cla()
  232. ax3.cla()
  233. assert not ax2.xaxis.get_visible()
  234. assert not ax2.patch.get_visible()
  235. assert ax2.yaxis.get_visible()
  236. assert ax3.xaxis.get_visible()
  237. assert not ax3.patch.get_visible()
  238. assert not ax3.yaxis.get_visible()
  239. assert ax.xaxis.get_visible()
  240. assert ax.patch.get_visible()
  241. assert ax.yaxis.get_visible()
  242. @pytest.mark.parametrize('twin', ('x', 'y'))
  243. @check_figures_equal(extensions=['png'], tol=0.19)
  244. def test_twin_logscale(fig_test, fig_ref, twin):
  245. twin_func = f'twin{twin}' # test twinx or twiny
  246. set_scale = f'set_{twin}scale'
  247. x = np.arange(1, 100)
  248. # Change scale after twinning.
  249. ax_test = fig_test.add_subplot(2, 1, 1)
  250. ax_twin = getattr(ax_test, twin_func)()
  251. getattr(ax_test, set_scale)('log')
  252. ax_twin.plot(x, x)
  253. # Twin after changing scale.
  254. ax_test = fig_test.add_subplot(2, 1, 2)
  255. getattr(ax_test, set_scale)('log')
  256. ax_twin = getattr(ax_test, twin_func)()
  257. ax_twin.plot(x, x)
  258. for i in [1, 2]:
  259. ax_ref = fig_ref.add_subplot(2, 1, i)
  260. getattr(ax_ref, set_scale)('log')
  261. ax_ref.plot(x, x)
  262. # This is a hack because twinned Axes double-draw the frame.
  263. # Remove this when that is fixed.
  264. Path = matplotlib.path.Path
  265. fig_ref.add_artist(
  266. matplotlib.patches.PathPatch(
  267. Path([[0, 0], [0, 1],
  268. [0, 1], [1, 1],
  269. [1, 1], [1, 0],
  270. [1, 0], [0, 0]],
  271. [Path.MOVETO, Path.LINETO] * 4),
  272. transform=ax_ref.transAxes,
  273. facecolor='none',
  274. edgecolor=mpl.rcParams['axes.edgecolor'],
  275. linewidth=mpl.rcParams['axes.linewidth'],
  276. capstyle='projecting'))
  277. remove_ticks_and_titles(fig_test)
  278. remove_ticks_and_titles(fig_ref)
  279. @image_comparison(['twin_autoscale.png'])
  280. def test_twinx_axis_scales():
  281. x = np.array([0, 0.5, 1])
  282. y = 0.5 * x
  283. x2 = np.array([0, 1, 2])
  284. y2 = 2 * x2
  285. fig = plt.figure()
  286. ax = fig.add_axes((0, 0, 1, 1), autoscalex_on=False, autoscaley_on=False)
  287. ax.plot(x, y, color='blue', lw=10)
  288. ax2 = plt.twinx(ax)
  289. ax2.plot(x2, y2, 'r--', lw=5)
  290. ax.margins(0, 0)
  291. ax2.margins(0, 0)
  292. def test_twin_inherit_autoscale_setting():
  293. fig, ax = plt.subplots()
  294. ax_x_on = ax.twinx()
  295. ax.set_autoscalex_on(False)
  296. ax_x_off = ax.twinx()
  297. assert ax_x_on.get_autoscalex_on()
  298. assert not ax_x_off.get_autoscalex_on()
  299. ax_y_on = ax.twiny()
  300. ax.set_autoscaley_on(False)
  301. ax_y_off = ax.twiny()
  302. assert ax_y_on.get_autoscaley_on()
  303. assert not ax_y_off.get_autoscaley_on()
  304. def test_inverted_cla():
  305. # GitHub PR #5450. Setting autoscale should reset
  306. # axes to be non-inverted.
  307. # plotting an image, then 1d graph, axis is now down
  308. fig = plt.figure(0)
  309. ax = fig.gca()
  310. # 1. test that a new axis is not inverted per default
  311. assert not ax.xaxis_inverted()
  312. assert not ax.yaxis_inverted()
  313. img = np.random.random((100, 100))
  314. ax.imshow(img)
  315. # 2. test that a image axis is inverted
  316. assert not ax.xaxis_inverted()
  317. assert ax.yaxis_inverted()
  318. # 3. test that clearing and plotting a line, axes are
  319. # not inverted
  320. ax.cla()
  321. x = np.linspace(0, 2*np.pi, 100)
  322. ax.plot(x, np.cos(x))
  323. assert not ax.xaxis_inverted()
  324. assert not ax.yaxis_inverted()
  325. # 4. autoscaling should not bring back axes to normal
  326. ax.cla()
  327. ax.imshow(img)
  328. plt.autoscale()
  329. assert not ax.xaxis_inverted()
  330. assert ax.yaxis_inverted()
  331. # 5. two shared axes. Inverting the master axis should invert the shared
  332. # axes; clearing the master axis should bring axes in shared
  333. # axes back to normal.
  334. ax0 = plt.subplot(211)
  335. ax1 = plt.subplot(212, sharey=ax0)
  336. ax0.yaxis.set_inverted(True)
  337. assert ax1.yaxis_inverted()
  338. ax1.plot(x, np.cos(x))
  339. ax0.cla()
  340. assert not ax1.yaxis_inverted()
  341. ax1.cla()
  342. # 6. clearing the nonmaster should not touch limits
  343. ax0.imshow(img)
  344. ax1.plot(x, np.cos(x))
  345. ax1.cla()
  346. assert ax.yaxis_inverted()
  347. # clean up
  348. plt.close(fig)
  349. @check_figures_equal(extensions=["png"])
  350. def test_minorticks_on_rcParams_both(fig_test, fig_ref):
  351. with matplotlib.rc_context({"xtick.minor.visible": True,
  352. "ytick.minor.visible": True}):
  353. ax_test = fig_test.subplots()
  354. ax_test.plot([0, 1], [0, 1])
  355. ax_ref = fig_ref.subplots()
  356. ax_ref.plot([0, 1], [0, 1])
  357. ax_ref.minorticks_on()
  358. @image_comparison(["autoscale_tiny_range"], remove_text=True)
  359. def test_autoscale_tiny_range():
  360. # github pull #904
  361. fig, axs = plt.subplots(2, 2)
  362. for i, ax in enumerate(axs.flat):
  363. y1 = 10**(-11 - i)
  364. ax.plot([0, 1], [1, 1 + y1])
  365. @pytest.mark.style('default')
  366. def test_autoscale_tight():
  367. fig, ax = plt.subplots(1, 1)
  368. ax.plot([1, 2, 3, 4])
  369. ax.autoscale(enable=True, axis='x', tight=False)
  370. ax.autoscale(enable=True, axis='y', tight=True)
  371. assert_allclose(ax.get_xlim(), (-0.15, 3.15))
  372. assert_allclose(ax.get_ylim(), (1.0, 4.0))
  373. @pytest.mark.style('default')
  374. def test_autoscale_log_shared():
  375. # related to github #7587
  376. # array starts at zero to trigger _minpos handling
  377. x = np.arange(100, dtype=float)
  378. fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
  379. ax1.loglog(x, x)
  380. ax2.semilogx(x, x)
  381. ax1.autoscale(tight=True)
  382. ax2.autoscale(tight=True)
  383. plt.draw()
  384. lims = (x[1], x[-1])
  385. assert_allclose(ax1.get_xlim(), lims)
  386. assert_allclose(ax1.get_ylim(), lims)
  387. assert_allclose(ax2.get_xlim(), lims)
  388. assert_allclose(ax2.get_ylim(), (x[0], x[-1]))
  389. @pytest.mark.style('default')
  390. def test_use_sticky_edges():
  391. fig, ax = plt.subplots()
  392. ax.imshow([[0, 1], [2, 3]], origin='lower')
  393. assert_allclose(ax.get_xlim(), (-0.5, 1.5))
  394. assert_allclose(ax.get_ylim(), (-0.5, 1.5))
  395. ax.use_sticky_edges = False
  396. ax.autoscale()
  397. xlim = (-0.5 - 2 * ax._xmargin, 1.5 + 2 * ax._xmargin)
  398. ylim = (-0.5 - 2 * ax._ymargin, 1.5 + 2 * ax._ymargin)
  399. assert_allclose(ax.get_xlim(), xlim)
  400. assert_allclose(ax.get_ylim(), ylim)
  401. # Make sure it is reversible:
  402. ax.use_sticky_edges = True
  403. ax.autoscale()
  404. assert_allclose(ax.get_xlim(), (-0.5, 1.5))
  405. assert_allclose(ax.get_ylim(), (-0.5, 1.5))
  406. @check_figures_equal(extensions=["png"])
  407. def test_sticky_shared_axes(fig_test, fig_ref):
  408. # Check that sticky edges work whether they are set in an axes that is a
  409. # "master" in a share, or an axes that is a "follower".
  410. Z = np.arange(15).reshape(3, 5)
  411. ax0 = fig_test.add_subplot(211)
  412. ax1 = fig_test.add_subplot(212, sharex=ax0)
  413. ax1.pcolormesh(Z)
  414. ax0 = fig_ref.add_subplot(212)
  415. ax1 = fig_ref.add_subplot(211, sharex=ax0)
  416. ax0.pcolormesh(Z)
  417. @image_comparison(['offset_points'], remove_text=True)
  418. def test_basic_annotate():
  419. # Setup some data
  420. t = np.arange(0.0, 5.0, 0.01)
  421. s = np.cos(2.0*np.pi * t)
  422. # Offset Points
  423. fig = plt.figure()
  424. ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-3, 5))
  425. line, = ax.plot(t, s, lw=3, color='purple')
  426. ax.annotate('local max', xy=(3, 1), xycoords='data',
  427. xytext=(3, 3), textcoords='offset points')
  428. def test_annotate_parameter_warn():
  429. fig, ax = plt.subplots()
  430. with pytest.warns(MatplotlibDeprecationWarning,
  431. match=r"The \'s\' parameter of annotate\(\) "
  432. "has been renamed \'text\'"):
  433. ax.annotate(s='now named text', xy=(0, 1))
  434. @image_comparison(['arrow_simple.png'], remove_text=True)
  435. def test_arrow_simple():
  436. # Simple image test for ax.arrow
  437. # kwargs that take discrete values
  438. length_includes_head = (True, False)
  439. shape = ('full', 'left', 'right')
  440. head_starts_at_zero = (True, False)
  441. # Create outer product of values
  442. kwargs = product(length_includes_head, shape, head_starts_at_zero)
  443. fig, axs = plt.subplots(3, 4)
  444. for i, (ax, kwarg) in enumerate(zip(axs.flat, kwargs)):
  445. ax.set_xlim(-2, 2)
  446. ax.set_ylim(-2, 2)
  447. # Unpack kwargs
  448. (length_includes_head, shape, head_starts_at_zero) = kwarg
  449. theta = 2 * np.pi * i / 12
  450. # Draw arrow
  451. ax.arrow(0, 0, np.sin(theta), np.cos(theta),
  452. width=theta/100,
  453. length_includes_head=length_includes_head,
  454. shape=shape,
  455. head_starts_at_zero=head_starts_at_zero,
  456. head_width=theta / 10,
  457. head_length=theta / 10)
  458. def test_arrow_empty():
  459. _, ax = plt.subplots()
  460. # Create an empty FancyArrow
  461. ax.arrow(0, 0, 0, 0, head_length=0)
  462. def test_arrow_in_view():
  463. _, ax = plt.subplots()
  464. ax.arrow(1, 1, 1, 1)
  465. assert ax.get_xlim() == (0.8, 2.2)
  466. assert ax.get_ylim() == (0.8, 2.2)
  467. def test_annotate_default_arrow():
  468. # Check that we can make an annotation arrow with only default properties.
  469. fig, ax = plt.subplots()
  470. ann = ax.annotate("foo", (0, 1), xytext=(2, 3))
  471. assert ann.arrow_patch is None
  472. ann = ax.annotate("foo", (0, 1), xytext=(2, 3), arrowprops={})
  473. assert ann.arrow_patch is not None
  474. @image_comparison(['fill_units.png'], savefig_kwarg={'dpi': 60})
  475. def test_fill_units():
  476. import matplotlib.testing.jpl_units as units
  477. units.register()
  478. # generate some data
  479. t = units.Epoch("ET", dt=datetime.datetime(2009, 4, 27))
  480. value = 10.0 * units.deg
  481. day = units.Duration("ET", 24.0 * 60.0 * 60.0)
  482. dt = np.arange('2009-04-27', '2009-04-29', dtype='datetime64[D]')
  483. dtn = mdates.date2num(dt)
  484. fig = plt.figure()
  485. # Top-Left
  486. ax1 = fig.add_subplot(221)
  487. ax1.plot([t], [value], yunits='deg', color='red')
  488. ind = [0, 0, 1, 1]
  489. ax1.fill(dtn[ind], [0.0, 0.0, 90.0, 0.0], 'b')
  490. # Top-Right
  491. ax2 = fig.add_subplot(222)
  492. ax2.plot([t], [value], yunits='deg', color='red')
  493. ax2.fill([t, t, t + day, t + day],
  494. [0.0, 0.0, 90.0, 0.0], 'b')
  495. # Bottom-Left
  496. ax3 = fig.add_subplot(223)
  497. ax3.plot([t], [value], yunits='deg', color='red')
  498. ax3.fill(dtn[ind],
  499. [0 * units.deg, 0 * units.deg, 90 * units.deg, 0 * units.deg],
  500. 'b')
  501. # Bottom-Right
  502. ax4 = fig.add_subplot(224)
  503. ax4.plot([t], [value], yunits='deg', color='red')
  504. ax4.fill([t, t, t + day, t + day],
  505. [0 * units.deg, 0 * units.deg, 90 * units.deg, 0 * units.deg],
  506. facecolor="blue")
  507. fig.autofmt_xdate()
  508. @image_comparison(['single_point', 'single_point'])
  509. def test_single_point():
  510. # Issue #1796: don't let lines.marker affect the grid
  511. matplotlib.rcParams['lines.marker'] = 'o'
  512. matplotlib.rcParams['axes.grid'] = True
  513. plt.figure()
  514. plt.subplot(211)
  515. plt.plot([0], [0], 'o')
  516. plt.subplot(212)
  517. plt.plot([1], [1], 'o')
  518. # Reuse testcase from above for a labeled data test
  519. data = {'a': [0], 'b': [1]}
  520. plt.figure()
  521. plt.subplot(211)
  522. plt.plot('a', 'a', 'o', data=data)
  523. plt.subplot(212)
  524. plt.plot('b', 'b', 'o', data=data)
  525. @image_comparison(['single_date.png'], style='mpl20')
  526. def test_single_date():
  527. # use former defaults to match existing baseline image
  528. plt.rcParams['axes.formatter.limits'] = -7, 7
  529. dt = mdates.date2num(np.datetime64('0000-12-31'))
  530. time1 = [721964.0]
  531. data1 = [-65.54]
  532. fig, ax = plt.subplots(2, 1)
  533. ax[0].plot_date(time1 + dt, data1, 'o', color='r')
  534. ax[1].plot(time1, data1, 'o', color='r')
  535. @check_figures_equal(extensions=["png"])
  536. def test_shaped_data(fig_test, fig_ref):
  537. row = np.arange(10).reshape((1, -1))
  538. col = np.arange(0, 100, 10).reshape((-1, 1))
  539. axs = fig_test.subplots(2)
  540. axs[0].plot(row) # Actually plots nothing (columns are single points).
  541. axs[1].plot(col) # Same as plotting 1d.
  542. axs = fig_ref.subplots(2)
  543. # xlim from the implicit "x=0", ylim from the row datalim.
  544. axs[0].set(xlim=(-.06, .06), ylim=(0, 9))
  545. axs[1].plot(col.ravel())
  546. def test_structured_data():
  547. # support for structured data
  548. pts = np.array([(1, 1), (2, 2)], dtype=[("ones", float), ("twos", float)])
  549. # this should not read second name as a format and raise ValueError
  550. axs = plt.figure().subplots(2)
  551. axs[0].plot("ones", "twos", data=pts)
  552. axs[1].plot("ones", "twos", "r", data=pts)
  553. @image_comparison(['aitoff_proj'], extensions=["png"],
  554. remove_text=True, style='mpl20')
  555. def test_aitoff_proj():
  556. """
  557. Test aitoff projection ref.:
  558. https://github.com/matplotlib/matplotlib/pull/14451
  559. """
  560. x = np.linspace(-np.pi, np.pi, 20)
  561. y = np.linspace(-np.pi / 2, np.pi / 2, 20)
  562. X, Y = np.meshgrid(x, y)
  563. fig, ax = plt.subplots(figsize=(8, 4.2),
  564. subplot_kw=dict(projection="aitoff"))
  565. ax.grid()
  566. ax.plot(X.flat, Y.flat, 'o', markersize=4)
  567. @image_comparison(['axvspan_epoch'])
  568. def test_axvspan_epoch():
  569. import matplotlib.testing.jpl_units as units
  570. units.register()
  571. # generate some data
  572. t0 = units.Epoch("ET", dt=datetime.datetime(2009, 1, 20))
  573. tf = units.Epoch("ET", dt=datetime.datetime(2009, 1, 21))
  574. dt = units.Duration("ET", units.day.convert("sec"))
  575. ax = plt.gca()
  576. plt.axvspan(t0, tf, facecolor="blue", alpha=0.25)
  577. ax.set_xlim(t0 - 5.0*dt, tf + 5.0*dt)
  578. @image_comparison(['axhspan_epoch'], tol=0.02)
  579. def test_axhspan_epoch():
  580. import matplotlib.testing.jpl_units as units
  581. units.register()
  582. # generate some data
  583. t0 = units.Epoch("ET", dt=datetime.datetime(2009, 1, 20))
  584. tf = units.Epoch("ET", dt=datetime.datetime(2009, 1, 21))
  585. dt = units.Duration("ET", units.day.convert("sec"))
  586. ax = plt.gca()
  587. ax.axhspan(t0, tf, facecolor="blue", alpha=0.25)
  588. ax.set_ylim(t0 - 5.0*dt, tf + 5.0*dt)
  589. @image_comparison(['hexbin_extent.png', 'hexbin_extent.png'], remove_text=True)
  590. def test_hexbin_extent():
  591. # this test exposes sf bug 2856228
  592. fig, ax = plt.subplots()
  593. data = (np.arange(2000) / 2000).reshape((2, 1000))
  594. x, y = data
  595. ax.hexbin(x, y, extent=[.1, .3, .6, .7])
  596. # Reuse testcase from above for a labeled data test
  597. data = {"x": x, "y": y}
  598. fig, ax = plt.subplots()
  599. ax.hexbin("x", "y", extent=[.1, .3, .6, .7], data=data)
  600. @image_comparison(['hexbin_empty.png'], remove_text=True)
  601. def test_hexbin_empty():
  602. # From #3886: creating hexbin from empty dataset raises ValueError
  603. ax = plt.gca()
  604. ax.hexbin([], [])
  605. def test_hexbin_pickable():
  606. # From #1973: Test that picking a hexbin collection works
  607. fig, ax = plt.subplots()
  608. data = (np.arange(200) / 200).reshape((2, 100))
  609. x, y = data
  610. hb = ax.hexbin(x, y, extent=[.1, .3, .6, .7], picker=-1)
  611. mouse_event = SimpleNamespace(x=400, y=300)
  612. assert hb.contains(mouse_event)[0]
  613. @image_comparison(['hexbin_log.png'], style='mpl20')
  614. def test_hexbin_log():
  615. # Issue #1636 (and also test log scaled colorbar)
  616. np.random.seed(19680801)
  617. n = 100000
  618. x = np.random.standard_normal(n)
  619. y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)
  620. y = np.power(2, y * 0.5)
  621. fig, ax = plt.subplots()
  622. h = ax.hexbin(x, y, yscale='log', bins='log')
  623. plt.colorbar(h)
  624. def test_inverted_limits():
  625. # Test gh:1553
  626. # Calling invert_xaxis prior to plotting should not disable autoscaling
  627. # while still maintaining the inverted direction
  628. fig, ax = plt.subplots()
  629. ax.invert_xaxis()
  630. ax.plot([-5, -3, 2, 4], [1, 2, -3, 5])
  631. assert ax.get_xlim() == (4, -5)
  632. assert ax.get_ylim() == (-3, 5)
  633. plt.close()
  634. fig, ax = plt.subplots()
  635. ax.invert_yaxis()
  636. ax.plot([-5, -3, 2, 4], [1, 2, -3, 5])
  637. assert ax.get_xlim() == (-5, 4)
  638. assert ax.get_ylim() == (5, -3)
  639. # Test inverting nonlinear axes.
  640. fig, ax = plt.subplots()
  641. ax.set_yscale("log")
  642. ax.set_ylim(10, 1)
  643. assert ax.get_ylim() == (10, 1)
  644. @image_comparison(['nonfinite_limits'])
  645. def test_nonfinite_limits():
  646. x = np.arange(0., np.e, 0.01)
  647. # silence divide by zero warning from log(0)
  648. with np.errstate(divide='ignore'):
  649. y = np.log(x)
  650. x[len(x)//2] = np.nan
  651. fig, ax = plt.subplots()
  652. ax.plot(x, y)
  653. @pytest.mark.style('default')
  654. @pytest.mark.parametrize('plot_fun',
  655. ['scatter', 'plot', 'fill_between'])
  656. @check_figures_equal(extensions=["png"])
  657. def test_limits_empty_data(plot_fun, fig_test, fig_ref):
  658. # Check that plotting empty data doesn't change autoscaling of dates
  659. x = np.arange("2010-01-01", "2011-01-01", dtype="datetime64[D]")
  660. ax_test = fig_test.subplots()
  661. ax_ref = fig_ref.subplots()
  662. getattr(ax_test, plot_fun)([], [])
  663. for ax in [ax_test, ax_ref]:
  664. getattr(ax, plot_fun)(x, range(len(x)), color='C0')
  665. @image_comparison(['imshow', 'imshow'], remove_text=True, style='mpl20')
  666. def test_imshow():
  667. # use former defaults to match existing baseline image
  668. matplotlib.rcParams['image.interpolation'] = 'nearest'
  669. # Create a NxN image
  670. N = 100
  671. (x, y) = np.indices((N, N))
  672. x -= N//2
  673. y -= N//2
  674. r = np.sqrt(x**2+y**2-x*y)
  675. # Create a contour plot at N/4 and extract both the clip path and transform
  676. fig, ax = plt.subplots()
  677. ax.imshow(r)
  678. # Reuse testcase from above for a labeled data test
  679. data = {"r": r}
  680. fig = plt.figure()
  681. ax = fig.add_subplot(111)
  682. ax.imshow("r", data=data)
  683. @image_comparison(['imshow_clip'], style='mpl20')
  684. def test_imshow_clip():
  685. # As originally reported by Gellule Xg <gellule.xg@free.fr>
  686. # use former defaults to match existing baseline image
  687. matplotlib.rcParams['image.interpolation'] = 'nearest'
  688. # Create a NxN image
  689. N = 100
  690. (x, y) = np.indices((N, N))
  691. x -= N//2
  692. y -= N//2
  693. r = np.sqrt(x**2+y**2-x*y)
  694. # Create a contour plot at N/4 and extract both the clip path and transform
  695. fig, ax = plt.subplots()
  696. c = ax.contour(r, [N/4])
  697. x = c.collections[0]
  698. clip_path = x.get_paths()[0]
  699. clip_transform = x.get_transform()
  700. clip_path = mtransforms.TransformedPath(clip_path, clip_transform)
  701. # Plot the image clipped by the contour
  702. ax.imshow(r, clip_path=clip_path)
  703. @check_figures_equal(extensions=["png"])
  704. def test_imshow_norm_vminvmax(fig_test, fig_ref):
  705. """Parameters vmin, vmax should be ignored if norm is given."""
  706. a = [[1, 2], [3, 4]]
  707. ax = fig_ref.subplots()
  708. ax.imshow(a, vmin=0, vmax=5)
  709. ax = fig_test.subplots()
  710. with pytest.warns(MatplotlibDeprecationWarning,
  711. match="Passing parameters norm and vmin/vmax "
  712. "simultaneously is deprecated."):
  713. ax.imshow(a, norm=mcolors.Normalize(-10, 10), vmin=0, vmax=5)
  714. @image_comparison(['polycollection_joinstyle'], remove_text=True)
  715. def test_polycollection_joinstyle():
  716. # Bug #2890979 reported by Matthew West
  717. fig, ax = plt.subplots()
  718. verts = np.array([[1, 1], [1, 2], [2, 2], [2, 1]])
  719. c = mpl.collections.PolyCollection([verts], linewidths=40)
  720. ax.add_collection(c)
  721. ax.set_xbound(0, 3)
  722. ax.set_ybound(0, 3)
  723. @pytest.mark.parametrize(
  724. 'x, y1, y2', [
  725. (np.zeros((2, 2)), 3, 3),
  726. (np.arange(0.0, 2, 0.02), np.zeros((2, 2)), 3),
  727. (np.arange(0.0, 2, 0.02), 3, np.zeros((2, 2)))
  728. ], ids=[
  729. '2d_x_input',
  730. '2d_y1_input',
  731. '2d_y2_input'
  732. ]
  733. )
  734. def test_fill_between_input(x, y1, y2):
  735. fig, ax = plt.subplots()
  736. with pytest.raises(ValueError):
  737. ax.fill_between(x, y1, y2)
  738. @pytest.mark.parametrize(
  739. 'y, x1, x2', [
  740. (np.zeros((2, 2)), 3, 3),
  741. (np.arange(0.0, 2, 0.02), np.zeros((2, 2)), 3),
  742. (np.arange(0.0, 2, 0.02), 3, np.zeros((2, 2)))
  743. ], ids=[
  744. '2d_y_input',
  745. '2d_x1_input',
  746. '2d_x2_input'
  747. ]
  748. )
  749. def test_fill_betweenx_input(y, x1, x2):
  750. fig, ax = plt.subplots()
  751. with pytest.raises(ValueError):
  752. ax.fill_betweenx(y, x1, x2)
  753. @image_comparison(['fill_between_interpolate'], remove_text=True)
  754. def test_fill_between_interpolate():
  755. x = np.arange(0.0, 2, 0.02)
  756. y1 = np.sin(2*np.pi*x)
  757. y2 = 1.2*np.sin(4*np.pi*x)
  758. fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
  759. ax1.plot(x, y1, x, y2, color='black')
  760. ax1.fill_between(x, y1, y2, where=y2 >= y1, facecolor='white', hatch='/',
  761. interpolate=True)
  762. ax1.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red',
  763. interpolate=True)
  764. # Test support for masked arrays.
  765. y2 = np.ma.masked_greater(y2, 1.0)
  766. # Test that plotting works for masked arrays with the first element masked
  767. y2[0] = np.ma.masked
  768. ax2.plot(x, y1, x, y2, color='black')
  769. ax2.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green',
  770. interpolate=True)
  771. ax2.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red',
  772. interpolate=True)
  773. @image_comparison(['fill_between_interpolate_decreasing'],
  774. style='mpl20', remove_text=True)
  775. def test_fill_between_interpolate_decreasing():
  776. p = np.array([724.3, 700, 655])
  777. t = np.array([9.4, 7, 2.2])
  778. prof = np.array([7.9, 6.6, 3.8])
  779. fig, ax = plt.subplots(figsize=(9, 9))
  780. ax.plot(t, p, 'tab:red')
  781. ax.plot(prof, p, 'k')
  782. ax.fill_betweenx(p, t, prof, where=prof < t,
  783. facecolor='blue', interpolate=True, alpha=0.4)
  784. ax.fill_betweenx(p, t, prof, where=prof > t,
  785. facecolor='red', interpolate=True, alpha=0.4)
  786. ax.set_xlim(0, 30)
  787. ax.set_ylim(800, 600)
  788. # test_symlog and test_symlog2 used to have baseline images in all three
  789. # formats, but the png and svg baselines got invalidated by the removal of
  790. # minor tick overstriking.
  791. @image_comparison(['symlog.pdf'])
  792. def test_symlog():
  793. x = np.array([0, 1, 2, 4, 6, 9, 12, 24])
  794. y = np.array([1000000, 500000, 100000, 100, 5, 0, 0, 0])
  795. fig, ax = plt.subplots()
  796. ax.plot(x, y)
  797. ax.set_yscale('symlog')
  798. ax.set_xscale('linear')
  799. ax.set_ylim(-1, 10000000)
  800. @image_comparison(['symlog2.pdf'], remove_text=True)
  801. def test_symlog2():
  802. # Numbers from -50 to 50, with 0.1 as step
  803. x = np.arange(-50, 50, 0.001)
  804. fig, axs = plt.subplots(5, 1)
  805. for ax, linthresh in zip(axs, [20., 2., 1., 0.1, 0.01]):
  806. ax.plot(x, x)
  807. ax.set_xscale('symlog', linthresh=linthresh)
  808. ax.grid(True)
  809. axs[-1].set_ylim(-0.1, 0.1)
  810. def test_pcolorargs_5205():
  811. # Smoketest to catch issue found in gh:5205
  812. x = [-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5]
  813. y = [-1.5, -1.25, -1.0, -0.75, -0.5, -0.25, 0,
  814. 0.25, 0.5, 0.75, 1.0, 1.25, 1.5]
  815. X, Y = np.meshgrid(x, y)
  816. Z = np.hypot(X, Y)
  817. plt.pcolor(Z)
  818. plt.pcolor(list(Z))
  819. plt.pcolor(x, y, Z[:-1, :-1])
  820. plt.pcolor(X, Y, list(Z[:-1, :-1]))
  821. @image_comparison(['pcolormesh'], remove_text=True)
  822. def test_pcolormesh():
  823. n = 12
  824. x = np.linspace(-1.5, 1.5, n)
  825. y = np.linspace(-1.5, 1.5, n*2)
  826. X, Y = np.meshgrid(x, y)
  827. Qx = np.cos(Y) - np.cos(X)
  828. Qz = np.sin(Y) + np.sin(X)
  829. Qx = (Qx + 1.1)
  830. Z = np.hypot(X, Y) / 5
  831. Z = (Z - Z.min()) / Z.ptp()
  832. # The color array can include masked values:
  833. Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z)
  834. fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
  835. ax1.pcolormesh(Qx, Qz, Z[:-1, :-1], lw=0.5, edgecolors='k')
  836. ax2.pcolormesh(Qx, Qz, Z[:-1, :-1], lw=2, edgecolors=['b', 'w'])
  837. ax3.pcolormesh(Qx, Qz, Z, shading="gouraud")
  838. @image_comparison(['pcolormesh_alpha'], extensions=["png", "pdf"],
  839. remove_text=True)
  840. def test_pcolormesh_alpha():
  841. n = 12
  842. X, Y = np.meshgrid(
  843. np.linspace(-1.5, 1.5, n),
  844. np.linspace(-1.5, 1.5, n*2)
  845. )
  846. Qx = X
  847. Qy = Y + np.sin(X)
  848. Z = np.hypot(X, Y) / 5
  849. Z = (Z - Z.min()) / Z.ptp()
  850. vir = plt.get_cmap("viridis", 16)
  851. # make another colormap with varying alpha
  852. colors = vir(np.arange(16))
  853. colors[:, 3] = 0.5 + 0.5*np.sin(np.arange(16))
  854. cmap = mcolors.ListedColormap(colors)
  855. fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
  856. for ax in ax1, ax2, ax3, ax4:
  857. ax.add_patch(mpatches.Rectangle(
  858. (0, -1.5), 1.5, 3, facecolor=[.7, .1, .1, .5], zorder=0
  859. ))
  860. # ax1, ax2: constant alpha
  861. ax1.pcolormesh(Qx, Qy, Z[:-1, :-1], cmap=vir, alpha=0.4,
  862. shading='flat', zorder=1)
  863. ax2.pcolormesh(Qx, Qy, Z, cmap=vir, alpha=0.4, shading='gouraud', zorder=1)
  864. # ax3, ax4: alpha from colormap
  865. ax3.pcolormesh(Qx, Qy, Z[:-1, :-1], cmap=cmap, shading='flat', zorder=1)
  866. ax4.pcolormesh(Qx, Qy, Z, cmap=cmap, shading='gouraud', zorder=1)
  867. @image_comparison(['pcolormesh_datetime_axis.png'],
  868. remove_text=False, style='mpl20')
  869. def test_pcolormesh_datetime_axis():
  870. fig = plt.figure()
  871. fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
  872. base = datetime.datetime(2013, 1, 1)
  873. x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
  874. y = np.arange(21)
  875. z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
  876. z = z1 * z2
  877. plt.subplot(221)
  878. plt.pcolormesh(x[:-1], y[:-1], z[:-1, :-1])
  879. plt.subplot(222)
  880. plt.pcolormesh(x, y, z)
  881. x = np.repeat(x[np.newaxis], 21, axis=0)
  882. y = np.repeat(y[:, np.newaxis], 21, axis=1)
  883. plt.subplot(223)
  884. plt.pcolormesh(x[:-1, :-1], y[:-1, :-1], z[:-1, :-1])
  885. plt.subplot(224)
  886. plt.pcolormesh(x, y, z)
  887. for ax in fig.get_axes():
  888. for label in ax.get_xticklabels():
  889. label.set_ha('right')
  890. label.set_rotation(30)
  891. @image_comparison(['pcolor_datetime_axis.png'],
  892. remove_text=False, style='mpl20')
  893. def test_pcolor_datetime_axis():
  894. fig = plt.figure()
  895. fig.subplots_adjust(hspace=0.4, top=0.98, bottom=.15)
  896. base = datetime.datetime(2013, 1, 1)
  897. x = np.array([base + datetime.timedelta(days=d) for d in range(21)])
  898. y = np.arange(21)
  899. z1, z2 = np.meshgrid(np.arange(20), np.arange(20))
  900. z = z1 * z2
  901. plt.subplot(221)
  902. plt.pcolor(x[:-1], y[:-1], z[:-1, :-1])
  903. plt.subplot(222)
  904. plt.pcolor(x, y, z)
  905. x = np.repeat(x[np.newaxis], 21, axis=0)
  906. y = np.repeat(y[:, np.newaxis], 21, axis=1)
  907. plt.subplot(223)
  908. plt.pcolor(x[:-1, :-1], y[:-1, :-1], z[:-1, :-1])
  909. plt.subplot(224)
  910. plt.pcolor(x, y, z)
  911. for ax in fig.get_axes():
  912. for label in ax.get_xticklabels():
  913. label.set_ha('right')
  914. label.set_rotation(30)
  915. def test_pcolorargs():
  916. n = 12
  917. x = np.linspace(-1.5, 1.5, n)
  918. y = np.linspace(-1.5, 1.5, n*2)
  919. X, Y = np.meshgrid(x, y)
  920. Z = np.hypot(X, Y) / 5
  921. _, ax = plt.subplots()
  922. with pytest.raises(TypeError):
  923. ax.pcolormesh(y, x, Z)
  924. with pytest.raises(TypeError):
  925. ax.pcolormesh(X, Y, Z.T)
  926. with pytest.raises(TypeError):
  927. ax.pcolormesh(x, y, Z[:-1, :-1], shading="gouraud")
  928. with pytest.raises(TypeError):
  929. ax.pcolormesh(X, Y, Z[:-1, :-1], shading="gouraud")
  930. x[0] = np.NaN
  931. with pytest.raises(ValueError):
  932. ax.pcolormesh(x, y, Z[:-1, :-1])
  933. with np.errstate(invalid='ignore'):
  934. x = np.ma.array(x, mask=(x < 0))
  935. with pytest.raises(ValueError):
  936. ax.pcolormesh(x, y, Z[:-1, :-1])
  937. # Expect a warning with non-increasing coordinates
  938. x = [359, 0, 1]
  939. y = [-10, 10]
  940. X, Y = np.meshgrid(x, y)
  941. Z = np.zeros(X.shape)
  942. with pytest.warns(UserWarning,
  943. match='are not monotonically increasing or decreasing'):
  944. ax.pcolormesh(X, Y, Z, shading='auto')
  945. @check_figures_equal(extensions=["png"])
  946. def test_pcolornearest(fig_test, fig_ref):
  947. ax = fig_test.subplots()
  948. x = np.arange(0, 10)
  949. y = np.arange(0, 3)
  950. np.random.seed(19680801)
  951. Z = np.random.randn(2, 9)
  952. ax.pcolormesh(x, y, Z, shading='flat')
  953. ax = fig_ref.subplots()
  954. # specify the centers
  955. x2 = x[:-1] + np.diff(x) / 2
  956. y2 = y[:-1] + np.diff(y) / 2
  957. ax.pcolormesh(x2, y2, Z, shading='nearest')
  958. @check_figures_equal(extensions=["png"])
  959. def test_pcolornearestunits(fig_test, fig_ref):
  960. ax = fig_test.subplots()
  961. x = [datetime.datetime.fromtimestamp(x * 3600) for x in range(10)]
  962. y = np.arange(0, 3)
  963. np.random.seed(19680801)
  964. Z = np.random.randn(2, 9)
  965. ax.pcolormesh(x, y, Z, shading='flat')
  966. ax = fig_ref.subplots()
  967. # specify the centers
  968. x2 = [datetime.datetime.fromtimestamp((x + 0.5) * 3600) for x in range(9)]
  969. y2 = y[:-1] + np.diff(y) / 2
  970. ax.pcolormesh(x2, y2, Z, shading='nearest')
  971. @check_figures_equal(extensions=["png"])
  972. def test_pcolordropdata(fig_test, fig_ref):
  973. ax = fig_test.subplots()
  974. x = np.arange(0, 10)
  975. y = np.arange(0, 4)
  976. np.random.seed(19680801)
  977. Z = np.random.randn(3, 9)
  978. # fake dropping the data
  979. ax.pcolormesh(x[:-1], y[:-1], Z[:-1, :-1], shading='flat')
  980. ax = fig_ref.subplots()
  981. # test dropping the data...
  982. x2 = x[:-1]
  983. y2 = y[:-1]
  984. with pytest.warns(MatplotlibDeprecationWarning):
  985. ax.pcolormesh(x2, y2, Z, shading='flat')
  986. @check_figures_equal(extensions=["png"])
  987. def test_pcolorauto(fig_test, fig_ref):
  988. ax = fig_test.subplots()
  989. x = np.arange(0, 10)
  990. y = np.arange(0, 4)
  991. np.random.seed(19680801)
  992. Z = np.random.randn(3, 9)
  993. ax.pcolormesh(x, y, Z, shading='auto')
  994. ax = fig_ref.subplots()
  995. # specify the centers
  996. x2 = x[:-1] + np.diff(x) / 2
  997. y2 = y[:-1] + np.diff(y) / 2
  998. ax.pcolormesh(x2, y2, Z, shading='auto')
  999. @image_comparison(['canonical'])
  1000. def test_canonical():
  1001. fig, ax = plt.subplots()
  1002. ax.plot([1, 2, 3])
  1003. @image_comparison(['arc_angles.png'], remove_text=True, style='default')
  1004. def test_arc_angles():
  1005. # Ellipse parameters
  1006. w = 2
  1007. h = 1
  1008. centre = (0.2, 0.5)
  1009. scale = 2
  1010. fig, axs = plt.subplots(3, 3)
  1011. for i, ax in enumerate(axs.flat):
  1012. theta2 = i * 360 / 9
  1013. theta1 = theta2 - 45
  1014. ax.add_patch(mpatches.Ellipse(centre, w, h, alpha=0.3))
  1015. ax.add_patch(mpatches.Arc(centre, w, h, theta1=theta1, theta2=theta2))
  1016. # Straight lines intersecting start and end of arc
  1017. ax.plot([scale * np.cos(np.deg2rad(theta1)) + centre[0],
  1018. centre[0],
  1019. scale * np.cos(np.deg2rad(theta2)) + centre[0]],
  1020. [scale * np.sin(np.deg2rad(theta1)) + centre[1],
  1021. centre[1],
  1022. scale * np.sin(np.deg2rad(theta2)) + centre[1]])
  1023. ax.set_xlim(-scale, scale)
  1024. ax.set_ylim(-scale, scale)
  1025. # This looks the same, but it triggers a different code path when it
  1026. # gets large enough.
  1027. w *= 10
  1028. h *= 10
  1029. centre = (centre[0] * 10, centre[1] * 10)
  1030. scale *= 10
  1031. @image_comparison(['arc_ellipse'], remove_text=True)
  1032. def test_arc_ellipse():
  1033. xcenter, ycenter = 0.38, 0.52
  1034. width, height = 1e-1, 3e-1
  1035. angle = -30
  1036. theta = np.deg2rad(np.arange(360))
  1037. x = width / 2. * np.cos(theta)
  1038. y = height / 2. * np.sin(theta)
  1039. rtheta = np.deg2rad(angle)
  1040. R = np.array([
  1041. [np.cos(rtheta), -np.sin(rtheta)],
  1042. [np.sin(rtheta), np.cos(rtheta)]])
  1043. x, y = np.dot(R, np.array([x, y]))
  1044. x += xcenter
  1045. y += ycenter
  1046. fig = plt.figure()
  1047. ax = fig.add_subplot(211, aspect='auto')
  1048. ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow',
  1049. linewidth=1, zorder=1)
  1050. e1 = mpatches.Arc((xcenter, ycenter), width, height,
  1051. angle=angle, linewidth=2, fill=False, zorder=2)
  1052. ax.add_patch(e1)
  1053. ax = fig.add_subplot(212, aspect='equal')
  1054. ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
  1055. e2 = mpatches.Arc((xcenter, ycenter), width, height,
  1056. angle=angle, linewidth=2, fill=False, zorder=2)
  1057. ax.add_patch(e2)
  1058. @image_comparison(['markevery'], remove_text=True)
  1059. def test_markevery():
  1060. x = np.linspace(0, 10, 100)
  1061. y = np.sin(x) * np.sqrt(x/10 + 0.5)
  1062. # check marker only plot
  1063. fig = plt.figure()
  1064. ax = fig.add_subplot(111)
  1065. ax.plot(x, y, 'o', label='default')
  1066. ax.plot(x, y, 'd', markevery=None, label='mark all')
  1067. ax.plot(x, y, 's', markevery=10, label='mark every 10')
  1068. ax.plot(x, y, '+', markevery=(5, 20), label='mark every 5 starting at 10')
  1069. ax.legend()
  1070. @image_comparison(['markevery_line'], remove_text=True)
  1071. def test_markevery_line():
  1072. x = np.linspace(0, 10, 100)
  1073. y = np.sin(x) * np.sqrt(x/10 + 0.5)
  1074. # check line/marker combos
  1075. fig = plt.figure()
  1076. ax = fig.add_subplot(111)
  1077. ax.plot(x, y, '-o', label='default')
  1078. ax.plot(x, y, '-d', markevery=None, label='mark all')
  1079. ax.plot(x, y, '-s', markevery=10, label='mark every 10')
  1080. ax.plot(x, y, '-+', markevery=(5, 20), label='mark every 5 starting at 10')
  1081. ax.legend()
  1082. @image_comparison(['markevery_linear_scales'], remove_text=True)
  1083. def test_markevery_linear_scales():
  1084. cases = [None,
  1085. 8,
  1086. (30, 8),
  1087. [16, 24, 30], [0, -1],
  1088. slice(100, 200, 3),
  1089. 0.1, 0.3, 1.5,
  1090. (0.0, 0.1), (0.45, 0.1)]
  1091. cols = 3
  1092. gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)
  1093. delta = 0.11
  1094. x = np.linspace(0, 10 - 2 * delta, 200) + delta
  1095. y = np.sin(x) + 1.0 + delta
  1096. for i, case in enumerate(cases):
  1097. row = (i // cols)
  1098. col = i % cols
  1099. plt.subplot(gs[row, col])
  1100. plt.title('markevery=%s' % str(case))
  1101. plt.plot(x, y, 'o', ls='-', ms=4, markevery=case)
  1102. @image_comparison(['markevery_linear_scales_zoomed'], remove_text=True)
  1103. def test_markevery_linear_scales_zoomed():
  1104. cases = [None,
  1105. 8,
  1106. (30, 8),
  1107. [16, 24, 30], [0, -1],
  1108. slice(100, 200, 3),
  1109. 0.1, 0.3, 1.5,
  1110. (0.0, 0.1), (0.45, 0.1)]
  1111. cols = 3
  1112. gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)
  1113. delta = 0.11
  1114. x = np.linspace(0, 10 - 2 * delta, 200) + delta
  1115. y = np.sin(x) + 1.0 + delta
  1116. for i, case in enumerate(cases):
  1117. row = (i // cols)
  1118. col = i % cols
  1119. plt.subplot(gs[row, col])
  1120. plt.title('markevery=%s' % str(case))
  1121. plt.plot(x, y, 'o', ls='-', ms=4, markevery=case)
  1122. plt.xlim((6, 6.7))
  1123. plt.ylim((1.1, 1.7))
  1124. @image_comparison(['markevery_log_scales'], remove_text=True)
  1125. def test_markevery_log_scales():
  1126. cases = [None,
  1127. 8,
  1128. (30, 8),
  1129. [16, 24, 30], [0, -1],
  1130. slice(100, 200, 3),
  1131. 0.1, 0.3, 1.5,
  1132. (0.0, 0.1), (0.45, 0.1)]
  1133. cols = 3
  1134. gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)
  1135. delta = 0.11
  1136. x = np.linspace(0, 10 - 2 * delta, 200) + delta
  1137. y = np.sin(x) + 1.0 + delta
  1138. for i, case in enumerate(cases):
  1139. row = (i // cols)
  1140. col = i % cols
  1141. plt.subplot(gs[row, col])
  1142. plt.title('markevery=%s' % str(case))
  1143. plt.xscale('log')
  1144. plt.yscale('log')
  1145. plt.plot(x, y, 'o', ls='-', ms=4, markevery=case)
  1146. @image_comparison(['markevery_polar'], style='default', remove_text=True)
  1147. def test_markevery_polar():
  1148. cases = [None,
  1149. 8,
  1150. (30, 8),
  1151. [16, 24, 30], [0, -1],
  1152. slice(100, 200, 3),
  1153. 0.1, 0.3, 1.5,
  1154. (0.0, 0.1), (0.45, 0.1)]
  1155. cols = 3
  1156. gs = matplotlib.gridspec.GridSpec(len(cases) // cols + 1, cols)
  1157. r = np.linspace(0, 3.0, 200)
  1158. theta = 2 * np.pi * r
  1159. for i, case in enumerate(cases):
  1160. row = (i // cols)
  1161. col = i % cols
  1162. plt.subplot(gs[row, col], polar=True)
  1163. plt.title('markevery=%s' % str(case))
  1164. plt.plot(theta, r, 'o', ls='-', ms=4, markevery=case)
  1165. @image_comparison(['marker_edges'], remove_text=True)
  1166. def test_marker_edges():
  1167. x = np.linspace(0, 1, 10)
  1168. fig = plt.figure()
  1169. ax = fig.add_subplot(111)
  1170. ax.plot(x, np.sin(x), 'y.', ms=30.0, mew=0, mec='r')
  1171. ax.plot(x+0.1, np.sin(x), 'y.', ms=30.0, mew=1, mec='r')
  1172. ax.plot(x+0.2, np.sin(x), 'y.', ms=30.0, mew=2, mec='b')
  1173. @image_comparison(['bar_tick_label_single.png', 'bar_tick_label_single.png'])
  1174. def test_bar_tick_label_single():
  1175. # From 2516: plot bar with array of string labels for x axis
  1176. ax = plt.gca()
  1177. ax.bar(0, 1, align='edge', tick_label='0')
  1178. # Reuse testcase from above for a labeled data test
  1179. data = {"a": 0, "b": 1}
  1180. fig = plt.figure()
  1181. ax = fig.add_subplot(111)
  1182. ax = plt.gca()
  1183. ax.bar("a", "b", align='edge', tick_label='0', data=data)
  1184. def test_nan_bar_values():
  1185. fig, ax = plt.subplots()
  1186. ax.bar([0, 1], [np.nan, 4])
  1187. def test_bar_ticklabel_fail():
  1188. fig, ax = plt.subplots()
  1189. ax.bar([], [])
  1190. @image_comparison(['bar_tick_label_multiple.png'])
  1191. def test_bar_tick_label_multiple():
  1192. # From 2516: plot bar with array of string labels for x axis
  1193. ax = plt.gca()
  1194. ax.bar([1, 2.5], [1, 2], width=[0.2, 0.5], tick_label=['a', 'b'],
  1195. align='center')
  1196. @image_comparison(['bar_tick_label_multiple_old_label_alignment.png'])
  1197. def test_bar_tick_label_multiple_old_alignment():
  1198. # Test that the alignment for class is backward compatible
  1199. matplotlib.rcParams["ytick.alignment"] = "center"
  1200. ax = plt.gca()
  1201. ax.bar([1, 2.5], [1, 2], width=[0.2, 0.5], tick_label=['a', 'b'],
  1202. align='center')
  1203. @check_figures_equal(extensions=["png"])
  1204. def test_bar_decimal_center(fig_test, fig_ref):
  1205. ax = fig_test.subplots()
  1206. x0 = [1.5, 8.4, 5.3, 4.2]
  1207. y0 = [1.1, 2.2, 3.3, 4.4]
  1208. x = [Decimal(x) for x in x0]
  1209. y = [Decimal(y) for y in y0]
  1210. # Test image - vertical, align-center bar chart with Decimal() input
  1211. ax.bar(x, y, align='center')
  1212. # Reference image
  1213. ax = fig_ref.subplots()
  1214. ax.bar(x0, y0, align='center')
  1215. @check_figures_equal(extensions=["png"])
  1216. def test_barh_decimal_center(fig_test, fig_ref):
  1217. ax = fig_test.subplots()
  1218. x0 = [1.5, 8.4, 5.3, 4.2]
  1219. y0 = [1.1, 2.2, 3.3, 4.4]
  1220. x = [Decimal(x) for x in x0]
  1221. y = [Decimal(y) for y in y0]
  1222. # Test image - horizontal, align-center bar chart with Decimal() input
  1223. ax.barh(x, y, height=[0.5, 0.5, 1, 1], align='center')
  1224. # Reference image
  1225. ax = fig_ref.subplots()
  1226. ax.barh(x0, y0, height=[0.5, 0.5, 1, 1], align='center')
  1227. @check_figures_equal(extensions=["png"])
  1228. def test_bar_decimal_width(fig_test, fig_ref):
  1229. x = [1.5, 8.4, 5.3, 4.2]
  1230. y = [1.1, 2.2, 3.3, 4.4]
  1231. w0 = [0.7, 1.45, 1, 2]
  1232. w = [Decimal(i) for i in w0]
  1233. # Test image - vertical bar chart with Decimal() width
  1234. ax = fig_test.subplots()
  1235. ax.bar(x, y, width=w, align='center')
  1236. # Reference image
  1237. ax = fig_ref.subplots()
  1238. ax.bar(x, y, width=w0, align='center')
  1239. @check_figures_equal(extensions=["png"])
  1240. def test_barh_decimal_height(fig_test, fig_ref):
  1241. x = [1.5, 8.4, 5.3, 4.2]
  1242. y = [1.1, 2.2, 3.3, 4.4]
  1243. h0 = [0.7, 1.45, 1, 2]
  1244. h = [Decimal(i) for i in h0]
  1245. # Test image - horizontal bar chart with Decimal() height
  1246. ax = fig_test.subplots()
  1247. ax.barh(x, y, height=h, align='center')
  1248. # Reference image
  1249. ax = fig_ref.subplots()
  1250. ax.barh(x, y, height=h0, align='center')
  1251. def test_bar_color_none_alpha():
  1252. ax = plt.gca()
  1253. rects = ax.bar([1, 2], [2, 4], alpha=0.3, color='none', edgecolor='r')
  1254. for rect in rects:
  1255. assert rect.get_facecolor() == (0, 0, 0, 0)
  1256. assert rect.get_edgecolor() == (1, 0, 0, 0.3)
  1257. def test_bar_edgecolor_none_alpha():
  1258. ax = plt.gca()
  1259. rects = ax.bar([1, 2], [2, 4], alpha=0.3, color='r', edgecolor='none')
  1260. for rect in rects:
  1261. assert rect.get_facecolor() == (1, 0, 0, 0.3)
  1262. assert rect.get_edgecolor() == (0, 0, 0, 0)
  1263. @image_comparison(['barh_tick_label.png'])
  1264. def test_barh_tick_label():
  1265. # From 2516: plot barh with array of string labels for y axis
  1266. ax = plt.gca()
  1267. ax.barh([1, 2.5], [1, 2], height=[0.2, 0.5], tick_label=['a', 'b'],
  1268. align='center')
  1269. def test_bar_timedelta():
  1270. """Smoketest that bar can handle width and height in delta units."""
  1271. fig, ax = plt.subplots()
  1272. ax.bar(datetime.datetime(2018, 1, 1), 1.,
  1273. width=datetime.timedelta(hours=3))
  1274. ax.bar(datetime.datetime(2018, 1, 1), 1.,
  1275. xerr=datetime.timedelta(hours=2),
  1276. width=datetime.timedelta(hours=3))
  1277. fig, ax = plt.subplots()
  1278. ax.barh(datetime.datetime(2018, 1, 1), 1,
  1279. height=datetime.timedelta(hours=3))
  1280. ax.barh(datetime.datetime(2018, 1, 1), 1,
  1281. height=datetime.timedelta(hours=3),
  1282. yerr=datetime.timedelta(hours=2))
  1283. fig, ax = plt.subplots()
  1284. ax.barh([datetime.datetime(2018, 1, 1), datetime.datetime(2018, 1, 1)],
  1285. np.array([1, 1.5]),
  1286. height=datetime.timedelta(hours=3))
  1287. ax.barh([datetime.datetime(2018, 1, 1), datetime.datetime(2018, 1, 1)],
  1288. np.array([1, 1.5]),
  1289. height=[datetime.timedelta(hours=t) for t in [1, 2]])
  1290. ax.broken_barh([(datetime.datetime(2018, 1, 1),
  1291. datetime.timedelta(hours=1))],
  1292. (10, 20))
  1293. def test_boxplot_dates_pandas(pd):
  1294. # smoke test for boxplot and dates in pandas
  1295. data = np.random.rand(5, 2)
  1296. years = pd.date_range('1/1/2000',
  1297. periods=2, freq=pd.DateOffset(years=1)).year
  1298. plt.figure()
  1299. plt.boxplot(data, positions=years)
  1300. def test_bar_pandas(pd):
  1301. # Smoke test for pandas
  1302. df = pd.DataFrame(
  1303. {'year': [2018, 2018, 2018],
  1304. 'month': [1, 1, 1],
  1305. 'day': [1, 2, 3],
  1306. 'value': [1, 2, 3]})
  1307. df['date'] = pd.to_datetime(df[['year', 'month', 'day']])
  1308. monthly = df[['date', 'value']].groupby(['date']).sum()
  1309. dates = monthly.index
  1310. forecast = monthly['value']
  1311. baseline = monthly['value']
  1312. fig, ax = plt.subplots()
  1313. ax.bar(dates, forecast, width=10, align='center')
  1314. ax.plot(dates, baseline, color='orange', lw=4)
  1315. def test_bar_pandas_indexed(pd):
  1316. # Smoke test for indexed pandas
  1317. df = pd.DataFrame({"x": [1., 2., 3.], "width": [.2, .4, .6]},
  1318. index=[1, 2, 3])
  1319. fig, ax = plt.subplots()
  1320. ax.bar(df.x, 1., width=df.width)
  1321. def test_pandas_minimal_plot(pd):
  1322. # smoke test that series and index objcets do not warn
  1323. x = pd.Series([1, 2], dtype="float64")
  1324. plt.plot(x, x)
  1325. plt.plot(x.index, x)
  1326. plt.plot(x)
  1327. plt.plot(x.index)
  1328. @image_comparison(['hist_log'], remove_text=True)
  1329. def test_hist_log():
  1330. data0 = np.linspace(0, 1, 200)**3
  1331. data = np.concatenate([1 - data0, 1 + data0])
  1332. fig = plt.figure()
  1333. ax = fig.add_subplot(111)
  1334. ax.hist(data, fill=False, log=True)
  1335. @check_figures_equal(extensions=["png"])
  1336. def test_hist_log_2(fig_test, fig_ref):
  1337. axs_test = fig_test.subplots(2, 3)
  1338. axs_ref = fig_ref.subplots(2, 3)
  1339. for i, histtype in enumerate(["bar", "step", "stepfilled"]):
  1340. # Set log scale, then call hist().
  1341. axs_test[0, i].set_yscale("log")
  1342. axs_test[0, i].hist(1, 1, histtype=histtype)
  1343. # Call hist(), then set log scale.
  1344. axs_test[1, i].hist(1, 1, histtype=histtype)
  1345. axs_test[1, i].set_yscale("log")
  1346. # Use hist(..., log=True).
  1347. for ax in axs_ref[:, i]:
  1348. ax.hist(1, 1, log=True, histtype=histtype)
  1349. def test_hist_log_barstacked():
  1350. fig, axs = plt.subplots(2)
  1351. axs[0].hist([[0], [0, 1]], 2, histtype="barstacked")
  1352. axs[0].set_yscale("log")
  1353. axs[1].hist([0, 0, 1], 2, histtype="barstacked")
  1354. axs[1].set_yscale("log")
  1355. fig.canvas.draw()
  1356. assert axs[0].get_ylim() == axs[1].get_ylim()
  1357. @image_comparison(['hist_bar_empty.png'], remove_text=True)
  1358. def test_hist_bar_empty():
  1359. # From #3886: creating hist from empty dataset raises ValueError
  1360. ax = plt.gca()
  1361. ax.hist([], histtype='bar')
  1362. @image_comparison(['hist_step_empty.png'], remove_text=True)
  1363. def test_hist_step_empty():
  1364. # From #3886: creating hist from empty dataset raises ValueError
  1365. ax = plt.gca()
  1366. ax.hist([], histtype='step')
  1367. @image_comparison(['hist_step_filled.png'], remove_text=True)
  1368. def test_hist_step_filled():
  1369. np.random.seed(0)
  1370. x = np.random.randn(1000, 3)
  1371. n_bins = 10
  1372. kwargs = [{'fill': True}, {'fill': False}, {'fill': None}, {}]*2
  1373. types = ['step']*4+['stepfilled']*4
  1374. fig, axs = plt.subplots(nrows=2, ncols=4)
  1375. for kg, _type, ax in zip(kwargs, types, axs.flat):
  1376. ax.hist(x, n_bins, histtype=_type, stacked=True, **kg)
  1377. ax.set_title('%s/%s' % (kg, _type))
  1378. ax.set_ylim(bottom=-50)
  1379. patches = axs[0, 0].patches
  1380. assert all(p.get_facecolor() == p.get_edgecolor() for p in patches)
  1381. @image_comparison(['hist_density.png'])
  1382. def test_hist_density():
  1383. np.random.seed(19680801)
  1384. data = np.random.standard_normal(2000)
  1385. fig, ax = plt.subplots()
  1386. ax.hist(data, density=True)
  1387. def test_hist_unequal_bins_density():
  1388. # Test correct behavior of normalized histogram with unequal bins
  1389. # https://github.com/matplotlib/matplotlib/issues/9557
  1390. rng = np.random.RandomState(57483)
  1391. t = rng.randn(100)
  1392. bins = [-3, -1, -0.5, 0, 1, 5]
  1393. mpl_heights, _, _ = plt.hist(t, bins=bins, density=True)
  1394. np_heights, _ = np.histogram(t, bins=bins, density=True)
  1395. assert_allclose(mpl_heights, np_heights)
  1396. def test_hist_datetime_datasets():
  1397. data = [[datetime.datetime(2017, 1, 1), datetime.datetime(2017, 1, 1)],
  1398. [datetime.datetime(2017, 1, 1), datetime.datetime(2017, 1, 2)]]
  1399. fig, ax = plt.subplots()
  1400. ax.hist(data, stacked=True)
  1401. ax.hist(data, stacked=False)
  1402. @pytest.mark.parametrize("bins_preprocess",
  1403. [mpl.dates.date2num,
  1404. lambda bins: bins,
  1405. lambda bins: np.asarray(bins).astype('datetime64')],
  1406. ids=['date2num', 'datetime.datetime',
  1407. 'np.datetime64'])
  1408. def test_hist_datetime_datasets_bins(bins_preprocess):
  1409. data = [[datetime.datetime(2019, 1, 5), datetime.datetime(2019, 1, 11),
  1410. datetime.datetime(2019, 2, 1), datetime.datetime(2019, 3, 1)],
  1411. [datetime.datetime(2019, 1, 11), datetime.datetime(2019, 2, 5),
  1412. datetime.datetime(2019, 2, 18), datetime.datetime(2019, 3, 1)]]
  1413. date_edges = [datetime.datetime(2019, 1, 1), datetime.datetime(2019, 2, 1),
  1414. datetime.datetime(2019, 3, 1)]
  1415. fig, ax = plt.subplots()
  1416. _, bins, _ = ax.hist(data, bins=bins_preprocess(date_edges), stacked=True)
  1417. np.testing.assert_allclose(bins, mpl.dates.date2num(date_edges))
  1418. _, bins, _ = ax.hist(data, bins=bins_preprocess(date_edges), stacked=False)
  1419. np.testing.assert_allclose(bins, mpl.dates.date2num(date_edges))
  1420. @pytest.mark.parametrize('data, expected_number_of_hists',
  1421. [([], 1),
  1422. ([[]], 1),
  1423. ([[], []], 2)])
  1424. def test_hist_with_empty_input(data, expected_number_of_hists):
  1425. hists, _, _ = plt.hist(data)
  1426. hists = np.asarray(hists)
  1427. if hists.ndim == 1:
  1428. assert 1 == expected_number_of_hists
  1429. else:
  1430. assert hists.shape[0] == expected_number_of_hists
  1431. @pytest.mark.parametrize("histtype, zorder",
  1432. [("bar", mpl.patches.Patch.zorder),
  1433. ("step", mpl.lines.Line2D.zorder),
  1434. ("stepfilled", mpl.patches.Patch.zorder)])
  1435. def test_hist_zorder(histtype, zorder):
  1436. ax = plt.figure().add_subplot()
  1437. ax.hist([1, 2], histtype=histtype)
  1438. assert ax.patches
  1439. for patch in ax.patches:
  1440. assert patch.get_zorder() == zorder
  1441. def contour_dat():
  1442. x = np.linspace(-3, 5, 150)
  1443. y = np.linspace(-3, 5, 120)
  1444. z = np.cos(x) + np.sin(y[:, np.newaxis])
  1445. return x, y, z
  1446. @image_comparison(['contour_hatching'], remove_text=True, style='mpl20')
  1447. def test_contour_hatching():
  1448. x, y, z = contour_dat()
  1449. fig = plt.figure()
  1450. ax = fig.add_subplot(111)
  1451. ax.contourf(x, y, z, 7, hatches=['/', '\\', '//', '-'],
  1452. cmap=plt.get_cmap('gray'),
  1453. extend='both', alpha=0.5)
  1454. @image_comparison(['contour_colorbar'], style='mpl20')
  1455. def test_contour_colorbar():
  1456. x, y, z = contour_dat()
  1457. fig = plt.figure()
  1458. ax = fig.add_subplot(111)
  1459. cs = ax.contourf(x, y, z, levels=np.arange(-1.8, 1.801, 0.2),
  1460. cmap=plt.get_cmap('RdBu'),
  1461. vmin=-0.6,
  1462. vmax=0.6,
  1463. extend='both')
  1464. cs1 = ax.contour(x, y, z, levels=np.arange(-2.2, -0.599, 0.2),
  1465. colors=['y'],
  1466. linestyles='solid',
  1467. linewidths=2)
  1468. cs2 = ax.contour(x, y, z, levels=np.arange(0.6, 2.2, 0.2),
  1469. colors=['c'],
  1470. linewidths=2)
  1471. cbar = fig.colorbar(cs, ax=ax)
  1472. cbar.add_lines(cs1)
  1473. cbar.add_lines(cs2, erase=False)
  1474. @image_comparison(['hist2d', 'hist2d'], remove_text=True, style='mpl20')
  1475. def test_hist2d():
  1476. np.random.seed(0)
  1477. # make it not symmetric in case we switch x and y axis
  1478. x = np.random.randn(100)*2+5
  1479. y = np.random.randn(100)-2
  1480. fig = plt.figure()
  1481. ax = fig.add_subplot(111)
  1482. ax.hist2d(x, y, bins=10, rasterized=True)
  1483. # Reuse testcase from above for a labeled data test
  1484. data = {"x": x, "y": y}
  1485. fig = plt.figure()
  1486. ax = fig.add_subplot(111)
  1487. ax.hist2d("x", "y", bins=10, data=data, rasterized=True)
  1488. @image_comparison(['hist2d_transpose'], remove_text=True, style='mpl20')
  1489. def test_hist2d_transpose():
  1490. np.random.seed(0)
  1491. # make sure the output from np.histogram is transposed before
  1492. # passing to pcolorfast
  1493. x = np.array([5]*100)
  1494. y = np.random.randn(100)-2
  1495. fig = plt.figure()
  1496. ax = fig.add_subplot(111)
  1497. ax.hist2d(x, y, bins=10, rasterized=True)
  1498. def test_hist2d_density():
  1499. x, y = np.random.random((2, 100))
  1500. ax = plt.figure().subplots()
  1501. for obj in [ax, plt]:
  1502. obj.hist2d(x, y, density=True)
  1503. class TestScatter:
  1504. @image_comparison(['scatter'], style='mpl20', remove_text=True)
  1505. def test_scatter_plot(self):
  1506. data = {"x": np.array([3, 4, 2, 6]), "y": np.array([2, 5, 2, 3]),
  1507. "c": ['r', 'y', 'b', 'lime'], "s": [24, 15, 19, 29],
  1508. "c2": ['0.5', '0.6', '0.7', '0.8']}
  1509. fig, ax = plt.subplots()
  1510. ax.scatter(data["x"] - 1., data["y"] - 1., c=data["c"], s=data["s"])
  1511. ax.scatter(data["x"] + 1., data["y"] + 1., c=data["c2"], s=data["s"])
  1512. ax.scatter("x", "y", c="c", s="s", data=data)
  1513. @image_comparison(['scatter_marker.png'], remove_text=True)
  1514. def test_scatter_marker(self):
  1515. fig, (ax0, ax1, ax2) = plt.subplots(ncols=3)
  1516. ax0.scatter([3, 4, 2, 6], [2, 5, 2, 3],
  1517. c=[(1, 0, 0), 'y', 'b', 'lime'],
  1518. s=[60, 50, 40, 30],
  1519. edgecolors=['k', 'r', 'g', 'b'],
  1520. marker='s')
  1521. ax1.scatter([3, 4, 2, 6], [2, 5, 2, 3],
  1522. c=[(1, 0, 0), 'y', 'b', 'lime'],
  1523. s=[60, 50, 40, 30],
  1524. edgecolors=['k', 'r', 'g', 'b'],
  1525. marker=mmarkers.MarkerStyle('o', fillstyle='top'))
  1526. # unit area ellipse
  1527. rx, ry = 3, 1
  1528. area = rx * ry * np.pi
  1529. theta = np.linspace(0, 2 * np.pi, 21)
  1530. verts = np.column_stack([np.cos(theta) * rx / area,
  1531. np.sin(theta) * ry / area])
  1532. ax2.scatter([3, 4, 2, 6], [2, 5, 2, 3],
  1533. c=[(1, 0, 0), 'y', 'b', 'lime'],
  1534. s=[60, 50, 40, 30],
  1535. edgecolors=['k', 'r', 'g', 'b'],
  1536. marker=verts)
  1537. @image_comparison(['scatter_2D'], remove_text=True, extensions=['png'])
  1538. def test_scatter_2D(self):
  1539. x = np.arange(3)
  1540. y = np.arange(2)
  1541. x, y = np.meshgrid(x, y)
  1542. z = x + y
  1543. fig, ax = plt.subplots()
  1544. ax.scatter(x, y, c=z, s=200, edgecolors='face')
  1545. @check_figures_equal(extensions=["png"])
  1546. def test_scatter_decimal(self, fig_test, fig_ref):
  1547. x0 = np.array([1.5, 8.4, 5.3, 4.2])
  1548. y0 = np.array([1.1, 2.2, 3.3, 4.4])
  1549. x = np.array([Decimal(i) for i in x0])
  1550. y = np.array([Decimal(i) for i in y0])
  1551. c = ['r', 'y', 'b', 'lime']
  1552. s = [24, 15, 19, 29]
  1553. # Test image - scatter plot with Decimal() input
  1554. ax = fig_test.subplots()
  1555. ax.scatter(x, y, c=c, s=s)
  1556. # Reference image
  1557. ax = fig_ref.subplots()
  1558. ax.scatter(x0, y0, c=c, s=s)
  1559. def test_scatter_color(self):
  1560. # Try to catch cases where 'c' kwarg should have been used.
  1561. with pytest.raises(ValueError):
  1562. plt.scatter([1, 2], [1, 2], color=[0.1, 0.2])
  1563. with pytest.raises(ValueError):
  1564. plt.scatter([1, 2, 3], [1, 2, 3], color=[1, 2, 3])
  1565. def test_scatter_size_arg_size(self):
  1566. x = np.arange(4)
  1567. with pytest.raises(ValueError):
  1568. plt.scatter(x, x, x[1:])
  1569. with pytest.raises(ValueError):
  1570. plt.scatter(x[1:], x[1:], x)
  1571. @check_figures_equal(extensions=["png"])
  1572. def test_scatter_invalid_color(self, fig_test, fig_ref):
  1573. ax = fig_test.subplots()
  1574. cmap = plt.get_cmap("viridis", 16)
  1575. cmap.set_bad("k", 1)
  1576. # Set a nonuniform size to prevent the last call to `scatter` (plotting
  1577. # the invalid points separately in fig_ref) from using the marker
  1578. # stamping fast path, which would result in slightly offset markers.
  1579. ax.scatter(range(4), range(4),
  1580. c=[1, np.nan, 2, np.nan], s=[1, 2, 3, 4],
  1581. cmap=cmap, plotnonfinite=True)
  1582. ax = fig_ref.subplots()
  1583. cmap = plt.get_cmap("viridis", 16)
  1584. ax.scatter([0, 2], [0, 2], c=[1, 2], s=[1, 3], cmap=cmap)
  1585. ax.scatter([1, 3], [1, 3], s=[2, 4], color="k")
  1586. @check_figures_equal(extensions=["png"])
  1587. def test_scatter_no_invalid_color(self, fig_test, fig_ref):
  1588. # With plotninfinite=False we plot only 2 points.
  1589. ax = fig_test.subplots()
  1590. cmap = plt.get_cmap("viridis", 16)
  1591. cmap.set_bad("k", 1)
  1592. ax.scatter(range(4), range(4),
  1593. c=[1, np.nan, 2, np.nan], s=[1, 2, 3, 4],
  1594. cmap=cmap, plotnonfinite=False)
  1595. ax = fig_ref.subplots()
  1596. ax.scatter([0, 2], [0, 2], c=[1, 2], s=[1, 3], cmap=cmap)
  1597. @check_figures_equal(extensions=["png"])
  1598. def test_scatter_norm_vminvmax(self, fig_test, fig_ref):
  1599. """Parameters vmin, vmax should be ignored if norm is given."""
  1600. x = [1, 2, 3]
  1601. ax = fig_ref.subplots()
  1602. ax.scatter(x, x, c=x, vmin=0, vmax=5)
  1603. ax = fig_test.subplots()
  1604. with pytest.warns(MatplotlibDeprecationWarning,
  1605. match="Passing parameters norm and vmin/vmax "
  1606. "simultaneously is deprecated."):
  1607. ax.scatter(x, x, c=x, norm=mcolors.Normalize(-10, 10),
  1608. vmin=0, vmax=5)
  1609. @check_figures_equal(extensions=["png"])
  1610. def test_scatter_single_point(self, fig_test, fig_ref):
  1611. ax = fig_test.subplots()
  1612. ax.scatter(1, 1, c=1)
  1613. ax = fig_ref.subplots()
  1614. ax.scatter([1], [1], c=[1])
  1615. @check_figures_equal(extensions=["png"])
  1616. def test_scatter_different_shapes(self, fig_test, fig_ref):
  1617. x = np.arange(10)
  1618. ax = fig_test.subplots()
  1619. ax.scatter(x, x.reshape(2, 5), c=x.reshape(5, 2))
  1620. ax = fig_ref.subplots()
  1621. ax.scatter(x.reshape(5, 2), x, c=x.reshape(2, 5))
  1622. # Parameters for *test_scatter_c*. NB: assuming that the
  1623. # scatter plot will have 4 elements. The tuple scheme is:
  1624. # (*c* parameter case, exception regexp key or None if no exception)
  1625. params_test_scatter_c = [
  1626. # single string:
  1627. ('0.5', None),
  1628. # Single letter-sequences
  1629. (["rgby"], "conversion"),
  1630. # Special cases
  1631. ("red", None),
  1632. ("none", None),
  1633. (None, None),
  1634. (["r", "g", "b", "none"], None),
  1635. # Non-valid color spec (FWIW, 'jaune' means yellow in French)
  1636. ("jaune", "conversion"),
  1637. (["jaune"], "conversion"), # wrong type before wrong size
  1638. (["jaune"]*4, "conversion"),
  1639. # Value-mapping like
  1640. ([0.5]*3, None), # should emit a warning for user's eyes though
  1641. ([0.5]*4, None), # NB: no warning as matching size allows mapping
  1642. ([0.5]*5, "shape"),
  1643. # list of strings:
  1644. (['0.5', '0.4', '0.6', '0.7'], None),
  1645. (['0.5', 'red', '0.6', 'C5'], None),
  1646. (['0.5', 0.5, '0.6', 'C5'], "conversion"),
  1647. # RGB values
  1648. ([[1, 0, 0]], None),
  1649. ([[1, 0, 0]]*3, "shape"),
  1650. ([[1, 0, 0]]*4, None),
  1651. ([[1, 0, 0]]*5, "shape"),
  1652. # RGBA values
  1653. ([[1, 0, 0, 0.5]], None),
  1654. ([[1, 0, 0, 0.5]]*3, "shape"),
  1655. ([[1, 0, 0, 0.5]]*4, None),
  1656. ([[1, 0, 0, 0.5]]*5, "shape"),
  1657. # Mix of valid color specs
  1658. ([[1, 0, 0, 0.5]]*3 + [[1, 0, 0]], None),
  1659. ([[1, 0, 0, 0.5], "red", "0.0"], "shape"),
  1660. ([[1, 0, 0, 0.5], "red", "0.0", "C5"], None),
  1661. ([[1, 0, 0, 0.5], "red", "0.0", "C5", [0, 1, 0]], "shape"),
  1662. # Mix of valid and non valid color specs
  1663. ([[1, 0, 0, 0.5], "red", "jaune"], "conversion"),
  1664. ([[1, 0, 0, 0.5], "red", "0.0", "jaune"], "conversion"),
  1665. ([[1, 0, 0, 0.5], "red", "0.0", "C5", "jaune"], "conversion"),
  1666. ]
  1667. @pytest.mark.parametrize('c_case, re_key', params_test_scatter_c)
  1668. def test_scatter_c(self, c_case, re_key):
  1669. def get_next_color():
  1670. return 'blue' # currently unused
  1671. xsize = 4
  1672. # Additional checking of *c* (introduced in #11383).
  1673. REGEXP = {
  1674. "shape": "^'c' argument has [0-9]+ elements", # shape mismatch
  1675. "conversion": "^'c' argument must be a color", # bad vals
  1676. }
  1677. if re_key is None:
  1678. mpl.axes.Axes._parse_scatter_color_args(
  1679. c=c_case, edgecolors="black", kwargs={}, xsize=xsize,
  1680. get_next_color_func=get_next_color)
  1681. else:
  1682. with pytest.raises(ValueError, match=REGEXP[re_key]):
  1683. mpl.axes.Axes._parse_scatter_color_args(
  1684. c=c_case, edgecolors="black", kwargs={}, xsize=xsize,
  1685. get_next_color_func=get_next_color)
  1686. @pytest.mark.style('default')
  1687. @check_figures_equal(extensions=["png"])
  1688. def test_scatter_single_color_c(self, fig_test, fig_ref):
  1689. rgb = [[1, 0.5, 0.05]]
  1690. rgba = [[1, 0.5, 0.05, .5]]
  1691. # set via color kwarg
  1692. ax_ref = fig_ref.subplots()
  1693. ax_ref.scatter(np.ones(3), range(3), color=rgb)
  1694. ax_ref.scatter(np.ones(4)*2, range(4), color=rgba)
  1695. # set via broadcasting via c
  1696. ax_test = fig_test.subplots()
  1697. ax_test.scatter(np.ones(3), range(3), c=rgb)
  1698. ax_test.scatter(np.ones(4)*2, range(4), c=rgba)
  1699. def test_scatter_linewidths(self):
  1700. x = np.arange(5)
  1701. fig, ax = plt.subplots()
  1702. for i in range(3):
  1703. pc = ax.scatter(x, np.full(5, i), c=f'C{i}', marker='x', s=100,
  1704. linewidths=i + 1)
  1705. assert pc.get_linewidths() == i + 1
  1706. pc = ax.scatter(x, np.full(5, 3), c='C3', marker='x', s=100,
  1707. linewidths=[*range(1, 5), None])
  1708. assert_array_equal(pc.get_linewidths(),
  1709. [*range(1, 5), mpl.rcParams['lines.linewidth']])
  1710. def _params(c=None, xsize=2, *, edgecolors=None, **kwargs):
  1711. return (c, edgecolors, kwargs if kwargs is not None else {}, xsize)
  1712. _result = namedtuple('_result', 'c, colors')
  1713. @pytest.mark.parametrize(
  1714. 'params, expected_result',
  1715. [(_params(),
  1716. _result(c='b', colors=np.array([[0, 0, 1, 1]]))),
  1717. (_params(c='r'),
  1718. _result(c='r', colors=np.array([[1, 0, 0, 1]]))),
  1719. (_params(c='r', colors='b'),
  1720. _result(c='r', colors=np.array([[1, 0, 0, 1]]))),
  1721. # color
  1722. (_params(color='b'),
  1723. _result(c='b', colors=np.array([[0, 0, 1, 1]]))),
  1724. (_params(color=['b', 'g']),
  1725. _result(c=['b', 'g'], colors=np.array([[0, 0, 1, 1], [0, .5, 0, 1]]))),
  1726. ])
  1727. def test_parse_scatter_color_args(params, expected_result):
  1728. def get_next_color():
  1729. return 'blue' # currently unused
  1730. c, colors, _edgecolors = mpl.axes.Axes._parse_scatter_color_args(
  1731. *params, get_next_color_func=get_next_color)
  1732. assert c == expected_result.c
  1733. assert_allclose(colors, expected_result.colors)
  1734. del _params
  1735. del _result
  1736. @pytest.mark.parametrize(
  1737. 'kwargs, expected_edgecolors',
  1738. [(dict(), None),
  1739. (dict(c='b'), None),
  1740. (dict(edgecolors='r'), 'r'),
  1741. (dict(edgecolors=['r', 'g']), ['r', 'g']),
  1742. (dict(edgecolor='r'), 'r'),
  1743. (dict(edgecolors='face'), 'face'),
  1744. (dict(edgecolors='none'), 'none'),
  1745. (dict(edgecolor='r', edgecolors='g'), 'r'),
  1746. (dict(c='b', edgecolor='r', edgecolors='g'), 'r'),
  1747. (dict(color='r'), 'r'),
  1748. (dict(color='r', edgecolor='g'), 'g'),
  1749. ])
  1750. def test_parse_scatter_color_args_edgecolors(kwargs, expected_edgecolors):
  1751. def get_next_color():
  1752. return 'blue' # currently unused
  1753. c = kwargs.pop('c', None)
  1754. edgecolors = kwargs.pop('edgecolors', None)
  1755. _, _, result_edgecolors = \
  1756. mpl.axes.Axes._parse_scatter_color_args(
  1757. c, edgecolors, kwargs, xsize=2, get_next_color_func=get_next_color)
  1758. assert result_edgecolors == expected_edgecolors
  1759. def test_parse_scatter_color_args_error():
  1760. def get_next_color():
  1761. return 'blue' # currently unused
  1762. with pytest.raises(ValueError,
  1763. match="RGBA values should be within 0-1 range"):
  1764. c = np.array([[0.1, 0.2, 0.7], [0.2, 0.4, 1.4]]) # value > 1
  1765. mpl.axes.Axes._parse_scatter_color_args(
  1766. c, None, kwargs={}, xsize=2, get_next_color_func=get_next_color)
  1767. def test_as_mpl_axes_api():
  1768. # tests the _as_mpl_axes api
  1769. from matplotlib.projections.polar import PolarAxes
  1770. class Polar:
  1771. def __init__(self):
  1772. self.theta_offset = 0
  1773. def _as_mpl_axes(self):
  1774. # implement the matplotlib axes interface
  1775. return PolarAxes, {'theta_offset': self.theta_offset}
  1776. prj = Polar()
  1777. prj2 = Polar()
  1778. prj2.theta_offset = np.pi
  1779. prj3 = Polar()
  1780. # testing axes creation with plt.axes
  1781. ax = plt.axes([0, 0, 1, 1], projection=prj)
  1782. assert type(ax) == PolarAxes
  1783. ax_via_gca = plt.gca(projection=prj)
  1784. assert ax_via_gca is ax
  1785. plt.close()
  1786. # testing axes creation with gca
  1787. ax = plt.gca(projection=prj)
  1788. assert type(ax) == mpl.axes._subplots.subplot_class_factory(PolarAxes)
  1789. ax_via_gca = plt.gca(projection=prj)
  1790. assert ax_via_gca is ax
  1791. # try getting the axes given a different polar projection
  1792. with pytest.warns(UserWarning) as rec:
  1793. ax_via_gca = plt.gca(projection=prj2)
  1794. assert len(rec) == 1
  1795. assert 'Requested projection is different' in str(rec[0].message)
  1796. assert ax_via_gca is not ax
  1797. assert ax.get_theta_offset() == 0
  1798. assert ax_via_gca.get_theta_offset() == np.pi
  1799. # try getting the axes given an == (not is) polar projection
  1800. with pytest.warns(UserWarning):
  1801. ax_via_gca = plt.gca(projection=prj3)
  1802. assert len(rec) == 1
  1803. assert 'Requested projection is different' in str(rec[0].message)
  1804. assert ax_via_gca is ax
  1805. plt.close()
  1806. # testing axes creation with subplot
  1807. ax = plt.subplot(121, projection=prj)
  1808. assert type(ax) == mpl.axes._subplots.subplot_class_factory(PolarAxes)
  1809. plt.close()
  1810. def test_pyplot_axes():
  1811. # test focusing of Axes in other Figure
  1812. fig1, ax1 = plt.subplots()
  1813. fig2, ax2 = plt.subplots()
  1814. plt.sca(ax1)
  1815. assert ax1 is plt.gca()
  1816. assert fig1 is plt.gcf()
  1817. plt.close(fig1)
  1818. plt.close(fig2)
  1819. @image_comparison(['log_scales'])
  1820. def test_log_scales():
  1821. fig = plt.figure()
  1822. ax = fig.add_subplot(1, 1, 1)
  1823. ax.plot(np.log(np.linspace(0.1, 100)))
  1824. ax.set_yscale('log', base=5.5)
  1825. ax.invert_yaxis()
  1826. ax.set_xscale('log', base=9.0)
  1827. def test_log_scales_no_data():
  1828. _, ax = plt.subplots()
  1829. ax.set(xscale="log", yscale="log")
  1830. ax.xaxis.set_major_locator(mticker.MultipleLocator(1))
  1831. assert ax.get_xlim() == ax.get_ylim() == (1, 10)
  1832. def test_log_scales_invalid():
  1833. fig = plt.figure()
  1834. ax = fig.add_subplot(1, 1, 1)
  1835. ax.set_xscale('log')
  1836. with pytest.warns(UserWarning, match='Attempted to set non-positive'):
  1837. ax.set_xlim(-1, 10)
  1838. ax.set_yscale('log')
  1839. with pytest.warns(UserWarning, match='Attempted to set non-positive'):
  1840. ax.set_ylim(-1, 10)
  1841. @image_comparison(['stackplot_test_image', 'stackplot_test_image'])
  1842. def test_stackplot():
  1843. fig = plt.figure()
  1844. x = np.linspace(0, 10, 10)
  1845. y1 = 1.0 * x
  1846. y2 = 2.0 * x + 1
  1847. y3 = 3.0 * x + 2
  1848. ax = fig.add_subplot(1, 1, 1)
  1849. ax.stackplot(x, y1, y2, y3)
  1850. ax.set_xlim((0, 10))
  1851. ax.set_ylim((0, 70))
  1852. # Reuse testcase from above for a labeled data test
  1853. data = {"x": x, "y1": y1, "y2": y2, "y3": y3}
  1854. fig = plt.figure()
  1855. ax = fig.add_subplot(1, 1, 1)
  1856. ax.stackplot("x", "y1", "y2", "y3", data=data)
  1857. ax.set_xlim((0, 10))
  1858. ax.set_ylim((0, 70))
  1859. @image_comparison(['stackplot_test_baseline'], remove_text=True)
  1860. def test_stackplot_baseline():
  1861. np.random.seed(0)
  1862. def layers(n, m):
  1863. a = np.zeros((m, n))
  1864. for i in range(n):
  1865. for j in range(5):
  1866. x = 1 / (.1 + np.random.random())
  1867. y = 2 * np.random.random() - .5
  1868. z = 10 / (.1 + np.random.random())
  1869. a[:, i] += x * np.exp(-((np.arange(m) / m - y) * z) ** 2)
  1870. return a
  1871. d = layers(3, 100)
  1872. d[50, :] = 0 # test for fixed weighted wiggle (issue #6313)
  1873. fig, axs = plt.subplots(2, 2)
  1874. axs[0, 0].stackplot(range(100), d.T, baseline='zero')
  1875. axs[0, 1].stackplot(range(100), d.T, baseline='sym')
  1876. axs[1, 0].stackplot(range(100), d.T, baseline='wiggle')
  1877. axs[1, 1].stackplot(range(100), d.T, baseline='weighted_wiggle')
  1878. def _bxp_test_helper(
  1879. stats_kwargs={}, transform_stats=lambda s: s, bxp_kwargs={}):
  1880. np.random.seed(937)
  1881. logstats = mpl.cbook.boxplot_stats(
  1882. np.random.lognormal(mean=1.25, sigma=1., size=(37, 4)), **stats_kwargs)
  1883. fig, ax = plt.subplots()
  1884. if bxp_kwargs.get('vert', True):
  1885. ax.set_yscale('log')
  1886. else:
  1887. ax.set_xscale('log')
  1888. # Work around baseline images generate back when bxp did not respect the
  1889. # boxplot.boxprops.linewidth rcParam when patch_artist is False.
  1890. if not bxp_kwargs.get('patch_artist', False):
  1891. mpl.rcParams['boxplot.boxprops.linewidth'] = \
  1892. mpl.rcParams['lines.linewidth']
  1893. ax.bxp(transform_stats(logstats), **bxp_kwargs)
  1894. @image_comparison(['bxp_baseline.png'],
  1895. savefig_kwarg={'dpi': 40},
  1896. style='default')
  1897. def test_bxp_baseline():
  1898. _bxp_test_helper()
  1899. @image_comparison(['bxp_rangewhis.png'],
  1900. savefig_kwarg={'dpi': 40},
  1901. style='default')
  1902. def test_bxp_rangewhis():
  1903. _bxp_test_helper(stats_kwargs=dict(whis=[0, 100]))
  1904. @image_comparison(['bxp_percentilewhis.png'],
  1905. savefig_kwarg={'dpi': 40},
  1906. style='default')
  1907. def test_bxp_percentilewhis():
  1908. _bxp_test_helper(stats_kwargs=dict(whis=[5, 95]))
  1909. @image_comparison(['bxp_with_xlabels.png'],
  1910. savefig_kwarg={'dpi': 40},
  1911. style='default')
  1912. def test_bxp_with_xlabels():
  1913. def transform(stats):
  1914. for s, label in zip(stats, list('ABCD')):
  1915. s['label'] = label
  1916. return stats
  1917. _bxp_test_helper(transform_stats=transform)
  1918. @image_comparison(['bxp_horizontal.png'],
  1919. remove_text=True,
  1920. savefig_kwarg={'dpi': 40},
  1921. style='default',
  1922. tol=0.1)
  1923. def test_bxp_horizontal():
  1924. _bxp_test_helper(bxp_kwargs=dict(vert=False))
  1925. @image_comparison(['bxp_with_ylabels.png'],
  1926. savefig_kwarg={'dpi': 40},
  1927. style='default',
  1928. tol=0.1)
  1929. def test_bxp_with_ylabels():
  1930. def transform(stats):
  1931. for s, label in zip(stats, list('ABCD')):
  1932. s['label'] = label
  1933. return stats
  1934. _bxp_test_helper(transform_stats=transform, bxp_kwargs=dict(vert=False))
  1935. @image_comparison(['bxp_patchartist.png'],
  1936. remove_text=True,
  1937. savefig_kwarg={'dpi': 40},
  1938. style='default')
  1939. def test_bxp_patchartist():
  1940. _bxp_test_helper(bxp_kwargs=dict(patch_artist=True))
  1941. @image_comparison(['bxp_custompatchartist.png'],
  1942. remove_text=True,
  1943. savefig_kwarg={'dpi': 100},
  1944. style='default')
  1945. def test_bxp_custompatchartist():
  1946. _bxp_test_helper(bxp_kwargs=dict(
  1947. patch_artist=True,
  1948. boxprops=dict(facecolor='yellow', edgecolor='green', ls=':')))
  1949. @image_comparison(['bxp_customoutlier.png'],
  1950. remove_text=True,
  1951. savefig_kwarg={'dpi': 40},
  1952. style='default')
  1953. def test_bxp_customoutlier():
  1954. _bxp_test_helper(bxp_kwargs=dict(
  1955. flierprops=dict(linestyle='none', marker='d', mfc='g')))
  1956. @image_comparison(['bxp_withmean_custompoint.png'],
  1957. remove_text=True,
  1958. savefig_kwarg={'dpi': 40},
  1959. style='default')
  1960. def test_bxp_showcustommean():
  1961. _bxp_test_helper(bxp_kwargs=dict(
  1962. showmeans=True,
  1963. meanprops=dict(linestyle='none', marker='d', mfc='green'),
  1964. ))
  1965. @image_comparison(['bxp_custombox.png'],
  1966. remove_text=True,
  1967. savefig_kwarg={'dpi': 40},
  1968. style='default')
  1969. def test_bxp_custombox():
  1970. _bxp_test_helper(bxp_kwargs=dict(
  1971. boxprops=dict(linestyle='--', color='b', lw=3)))
  1972. @image_comparison(['bxp_custommedian.png'],
  1973. remove_text=True,
  1974. savefig_kwarg={'dpi': 40},
  1975. style='default')
  1976. def test_bxp_custommedian():
  1977. _bxp_test_helper(bxp_kwargs=dict(
  1978. medianprops=dict(linestyle='--', color='b', lw=3)))
  1979. @image_comparison(['bxp_customcap.png'],
  1980. remove_text=True,
  1981. savefig_kwarg={'dpi': 40},
  1982. style='default')
  1983. def test_bxp_customcap():
  1984. _bxp_test_helper(bxp_kwargs=dict(
  1985. capprops=dict(linestyle='--', color='g', lw=3)))
  1986. @image_comparison(['bxp_customwhisker.png'],
  1987. remove_text=True,
  1988. savefig_kwarg={'dpi': 40},
  1989. style='default')
  1990. def test_bxp_customwhisker():
  1991. _bxp_test_helper(bxp_kwargs=dict(
  1992. whiskerprops=dict(linestyle='-', color='m', lw=3)))
  1993. @image_comparison(['bxp_withnotch.png'],
  1994. remove_text=True,
  1995. savefig_kwarg={'dpi': 40},
  1996. style='default')
  1997. def test_bxp_shownotches():
  1998. _bxp_test_helper(bxp_kwargs=dict(shownotches=True))
  1999. @image_comparison(['bxp_nocaps.png'],
  2000. remove_text=True,
  2001. savefig_kwarg={'dpi': 40},
  2002. style='default')
  2003. def test_bxp_nocaps():
  2004. _bxp_test_helper(bxp_kwargs=dict(showcaps=False))
  2005. @image_comparison(['bxp_nobox.png'],
  2006. remove_text=True,
  2007. savefig_kwarg={'dpi': 40},
  2008. style='default')
  2009. def test_bxp_nobox():
  2010. _bxp_test_helper(bxp_kwargs=dict(showbox=False))
  2011. @image_comparison(['bxp_no_flier_stats.png'],
  2012. remove_text=True,
  2013. savefig_kwarg={'dpi': 40},
  2014. style='default')
  2015. def test_bxp_no_flier_stats():
  2016. def transform(stats):
  2017. for s in stats:
  2018. s.pop('fliers', None)
  2019. return stats
  2020. _bxp_test_helper(transform_stats=transform,
  2021. bxp_kwargs=dict(showfliers=False))
  2022. @image_comparison(['bxp_withmean_point.png'],
  2023. remove_text=True,
  2024. savefig_kwarg={'dpi': 40},
  2025. style='default')
  2026. def test_bxp_showmean():
  2027. _bxp_test_helper(bxp_kwargs=dict(showmeans=True, meanline=False))
  2028. @image_comparison(['bxp_withmean_line.png'],
  2029. remove_text=True,
  2030. savefig_kwarg={'dpi': 40},
  2031. style='default')
  2032. def test_bxp_showmeanasline():
  2033. _bxp_test_helper(bxp_kwargs=dict(showmeans=True, meanline=True))
  2034. @image_comparison(['bxp_scalarwidth.png'],
  2035. remove_text=True,
  2036. savefig_kwarg={'dpi': 40},
  2037. style='default')
  2038. def test_bxp_scalarwidth():
  2039. _bxp_test_helper(bxp_kwargs=dict(widths=.25))
  2040. @image_comparison(['bxp_customwidths.png'],
  2041. remove_text=True,
  2042. savefig_kwarg={'dpi': 40},
  2043. style='default')
  2044. def test_bxp_customwidths():
  2045. _bxp_test_helper(bxp_kwargs=dict(widths=[0.10, 0.25, 0.65, 0.85]))
  2046. @image_comparison(['bxp_custompositions.png'],
  2047. remove_text=True,
  2048. savefig_kwarg={'dpi': 40},
  2049. style='default')
  2050. def test_bxp_custompositions():
  2051. _bxp_test_helper(bxp_kwargs=dict(positions=[1, 5, 6, 7]))
  2052. def test_bxp_bad_widths():
  2053. with pytest.raises(ValueError):
  2054. _bxp_test_helper(bxp_kwargs=dict(widths=[1]))
  2055. def test_bxp_bad_positions():
  2056. with pytest.raises(ValueError):
  2057. _bxp_test_helper(bxp_kwargs=dict(positions=[2, 3]))
  2058. @image_comparison(['boxplot', 'boxplot'], tol=1.28, style='default')
  2059. def test_boxplot():
  2060. # Randomness used for bootstrapping.
  2061. np.random.seed(937)
  2062. x = np.linspace(-7, 7, 140)
  2063. x = np.hstack([-25, x, 25])
  2064. fig, ax = plt.subplots()
  2065. ax.boxplot([x, x], bootstrap=10000, notch=1)
  2066. ax.set_ylim((-30, 30))
  2067. # Reuse testcase from above for a labeled data test
  2068. data = {"x": [x, x]}
  2069. fig, ax = plt.subplots()
  2070. ax.boxplot("x", bootstrap=10000, notch=1, data=data)
  2071. ax.set_ylim((-30, 30))
  2072. @image_comparison(['boxplot_sym2.png'], remove_text=True, style='default')
  2073. def test_boxplot_sym2():
  2074. # Randomness used for bootstrapping.
  2075. np.random.seed(937)
  2076. x = np.linspace(-7, 7, 140)
  2077. x = np.hstack([-25, x, 25])
  2078. fig, [ax1, ax2] = plt.subplots(1, 2)
  2079. ax1.boxplot([x, x], bootstrap=10000, sym='^')
  2080. ax1.set_ylim((-30, 30))
  2081. ax2.boxplot([x, x], bootstrap=10000, sym='g')
  2082. ax2.set_ylim((-30, 30))
  2083. @image_comparison(['boxplot_sym.png'],
  2084. remove_text=True,
  2085. savefig_kwarg={'dpi': 40},
  2086. style='default')
  2087. def test_boxplot_sym():
  2088. x = np.linspace(-7, 7, 140)
  2089. x = np.hstack([-25, x, 25])
  2090. fig, ax = plt.subplots()
  2091. ax.boxplot([x, x], sym='gs')
  2092. ax.set_ylim((-30, 30))
  2093. @image_comparison(['boxplot_autorange_false_whiskers.png',
  2094. 'boxplot_autorange_true_whiskers.png'],
  2095. style='default')
  2096. def test_boxplot_autorange_whiskers():
  2097. # Randomness used for bootstrapping.
  2098. np.random.seed(937)
  2099. x = np.ones(140)
  2100. x = np.hstack([0, x, 2])
  2101. fig1, ax1 = plt.subplots()
  2102. ax1.boxplot([x, x], bootstrap=10000, notch=1)
  2103. ax1.set_ylim((-5, 5))
  2104. fig2, ax2 = plt.subplots()
  2105. ax2.boxplot([x, x], bootstrap=10000, notch=1, autorange=True)
  2106. ax2.set_ylim((-5, 5))
  2107. def _rc_test_bxp_helper(ax, rc_dict):
  2108. x = np.linspace(-7, 7, 140)
  2109. x = np.hstack([-25, x, 25])
  2110. with matplotlib.rc_context(rc_dict):
  2111. ax.boxplot([x, x])
  2112. return ax
  2113. @image_comparison(['boxplot_rc_parameters'],
  2114. savefig_kwarg={'dpi': 100}, remove_text=True,
  2115. tol=1, style='default')
  2116. def test_boxplot_rc_parameters():
  2117. # Randomness used for bootstrapping.
  2118. np.random.seed(937)
  2119. fig, ax = plt.subplots(3)
  2120. rc_axis0 = {
  2121. 'boxplot.notch': True,
  2122. 'boxplot.whiskers': [5, 95],
  2123. 'boxplot.bootstrap': 10000,
  2124. 'boxplot.flierprops.color': 'b',
  2125. 'boxplot.flierprops.marker': 'o',
  2126. 'boxplot.flierprops.markerfacecolor': 'g',
  2127. 'boxplot.flierprops.markeredgecolor': 'b',
  2128. 'boxplot.flierprops.markersize': 5,
  2129. 'boxplot.flierprops.linestyle': '--',
  2130. 'boxplot.flierprops.linewidth': 2.0,
  2131. 'boxplot.boxprops.color': 'r',
  2132. 'boxplot.boxprops.linewidth': 2.0,
  2133. 'boxplot.boxprops.linestyle': '--',
  2134. 'boxplot.capprops.color': 'c',
  2135. 'boxplot.capprops.linewidth': 2.0,
  2136. 'boxplot.capprops.linestyle': '--',
  2137. 'boxplot.medianprops.color': 'k',
  2138. 'boxplot.medianprops.linewidth': 2.0,
  2139. 'boxplot.medianprops.linestyle': '--',
  2140. }
  2141. rc_axis1 = {
  2142. 'boxplot.vertical': False,
  2143. 'boxplot.whiskers': [0, 100],
  2144. 'boxplot.patchartist': True,
  2145. }
  2146. rc_axis2 = {
  2147. 'boxplot.whiskers': 2.0,
  2148. 'boxplot.showcaps': False,
  2149. 'boxplot.showbox': False,
  2150. 'boxplot.showfliers': False,
  2151. 'boxplot.showmeans': True,
  2152. 'boxplot.meanline': True,
  2153. 'boxplot.meanprops.color': 'c',
  2154. 'boxplot.meanprops.linewidth': 2.0,
  2155. 'boxplot.meanprops.linestyle': '--',
  2156. 'boxplot.whiskerprops.color': 'r',
  2157. 'boxplot.whiskerprops.linewidth': 2.0,
  2158. 'boxplot.whiskerprops.linestyle': '-.',
  2159. }
  2160. dict_list = [rc_axis0, rc_axis1, rc_axis2]
  2161. for axis, rc_axis in zip(ax, dict_list):
  2162. _rc_test_bxp_helper(axis, rc_axis)
  2163. assert (matplotlib.patches.PathPatch in
  2164. [type(t) for t in ax[1].get_children()])
  2165. @image_comparison(['boxplot_with_CIarray.png'],
  2166. remove_text=True, savefig_kwarg={'dpi': 40}, style='default')
  2167. def test_boxplot_with_CIarray():
  2168. # Randomness used for bootstrapping.
  2169. np.random.seed(937)
  2170. x = np.linspace(-7, 7, 140)
  2171. x = np.hstack([-25, x, 25])
  2172. fig = plt.figure()
  2173. ax = fig.add_subplot(111)
  2174. CIs = np.array([[-1.5, 3.], [-1., 3.5]])
  2175. # show a boxplot with Matplotlib medians and confidence intervals, and
  2176. # another with manual values
  2177. ax.boxplot([x, x], bootstrap=10000, usermedians=[None, 1.0],
  2178. conf_intervals=CIs, notch=1)
  2179. ax.set_ylim((-30, 30))
  2180. @image_comparison(['boxplot_no_inverted_whisker.png'],
  2181. remove_text=True, savefig_kwarg={'dpi': 40}, style='default')
  2182. def test_boxplot_no_weird_whisker():
  2183. x = np.array([3, 9000, 150, 88, 350, 200000, 1400, 960],
  2184. dtype=np.float64)
  2185. ax1 = plt.axes()
  2186. ax1.boxplot(x)
  2187. ax1.set_yscale('log')
  2188. ax1.yaxis.grid(False, which='minor')
  2189. ax1.xaxis.grid(False)
  2190. def test_boxplot_bad_medians():
  2191. x = np.linspace(-7, 7, 140)
  2192. x = np.hstack([-25, x, 25])
  2193. fig, ax = plt.subplots()
  2194. with pytest.raises(ValueError):
  2195. ax.boxplot(x, usermedians=[1, 2])
  2196. with pytest.raises(ValueError):
  2197. ax.boxplot([x, x], usermedians=[[1, 2], [1, 2]])
  2198. def test_boxplot_bad_ci():
  2199. x = np.linspace(-7, 7, 140)
  2200. x = np.hstack([-25, x, 25])
  2201. fig, ax = plt.subplots()
  2202. with pytest.raises(ValueError):
  2203. ax.boxplot([x, x], conf_intervals=[[1, 2]])
  2204. with pytest.raises(ValueError):
  2205. ax.boxplot([x, x], conf_intervals=[[1, 2], [1]])
  2206. def test_boxplot_zorder():
  2207. x = np.arange(10)
  2208. fix, ax = plt.subplots()
  2209. assert ax.boxplot(x)['boxes'][0].get_zorder() == 2
  2210. assert ax.boxplot(x, zorder=10)['boxes'][0].get_zorder() == 10
  2211. def test_boxplot_marker_behavior():
  2212. plt.rcParams['lines.marker'] = 's'
  2213. plt.rcParams['boxplot.flierprops.marker'] = 'o'
  2214. plt.rcParams['boxplot.meanprops.marker'] = '^'
  2215. fig, ax = plt.subplots()
  2216. test_data = np.arange(100)
  2217. test_data[-1] = 150 # a flier point
  2218. bxp_handle = ax.boxplot(test_data, showmeans=True)
  2219. for bxp_lines in ['whiskers', 'caps', 'boxes', 'medians']:
  2220. for each_line in bxp_handle[bxp_lines]:
  2221. # Ensure that the rcParams['lines.marker'] is overridden by ''
  2222. assert each_line.get_marker() == ''
  2223. # Ensure that markers for fliers and means aren't overridden with ''
  2224. assert bxp_handle['fliers'][0].get_marker() == 'o'
  2225. assert bxp_handle['means'][0].get_marker() == '^'
  2226. @image_comparison(['boxplot_mod_artists_after_plotting.png'],
  2227. remove_text=True, savefig_kwarg={'dpi': 40}, style='default')
  2228. def test_boxplot_mod_artist_after_plotting():
  2229. x = [0.15, 0.11, 0.06, 0.06, 0.12, 0.56, -0.56]
  2230. fig, ax = plt.subplots()
  2231. bp = ax.boxplot(x, sym="o")
  2232. for key in bp:
  2233. for obj in bp[key]:
  2234. obj.set_color('green')
  2235. @image_comparison(['violinplot_vert_baseline.png',
  2236. 'violinplot_vert_baseline.png'])
  2237. def test_vert_violinplot_baseline():
  2238. # First 9 digits of frac(sqrt(2))
  2239. np.random.seed(414213562)
  2240. data = [np.random.normal(size=100) for i in range(4)]
  2241. ax = plt.axes()
  2242. ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0,
  2243. showmedians=0)
  2244. # Reuse testcase from above for a labeled data test
  2245. data = {"d": data}
  2246. fig, ax = plt.subplots()
  2247. ax = plt.axes()
  2248. ax.violinplot("d", positions=range(4), showmeans=0, showextrema=0,
  2249. showmedians=0, data=data)
  2250. @image_comparison(['violinplot_vert_showmeans.png'])
  2251. def test_vert_violinplot_showmeans():
  2252. ax = plt.axes()
  2253. # First 9 digits of frac(sqrt(3))
  2254. np.random.seed(732050807)
  2255. data = [np.random.normal(size=100) for i in range(4)]
  2256. ax.violinplot(data, positions=range(4), showmeans=1, showextrema=0,
  2257. showmedians=0)
  2258. @image_comparison(['violinplot_vert_showextrema.png'])
  2259. def test_vert_violinplot_showextrema():
  2260. ax = plt.axes()
  2261. # First 9 digits of frac(sqrt(5))
  2262. np.random.seed(236067977)
  2263. data = [np.random.normal(size=100) for i in range(4)]
  2264. ax.violinplot(data, positions=range(4), showmeans=0, showextrema=1,
  2265. showmedians=0)
  2266. @image_comparison(['violinplot_vert_showmedians.png'])
  2267. def test_vert_violinplot_showmedians():
  2268. ax = plt.axes()
  2269. # First 9 digits of frac(sqrt(7))
  2270. np.random.seed(645751311)
  2271. data = [np.random.normal(size=100) for i in range(4)]
  2272. ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0,
  2273. showmedians=1)
  2274. @image_comparison(['violinplot_vert_showall.png'])
  2275. def test_vert_violinplot_showall():
  2276. ax = plt.axes()
  2277. # First 9 digits of frac(sqrt(11))
  2278. np.random.seed(316624790)
  2279. data = [np.random.normal(size=100) for i in range(4)]
  2280. ax.violinplot(data, positions=range(4), showmeans=1, showextrema=1,
  2281. showmedians=1,
  2282. quantiles=[[0.1, 0.9], [0.2, 0.8], [0.3, 0.7], [0.4, 0.6]])
  2283. @image_comparison(['violinplot_vert_custompoints_10.png'])
  2284. def test_vert_violinplot_custompoints_10():
  2285. ax = plt.axes()
  2286. # First 9 digits of frac(sqrt(13))
  2287. np.random.seed(605551275)
  2288. data = [np.random.normal(size=100) for i in range(4)]
  2289. ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0,
  2290. showmedians=0, points=10)
  2291. @image_comparison(['violinplot_vert_custompoints_200.png'])
  2292. def test_vert_violinplot_custompoints_200():
  2293. ax = plt.axes()
  2294. # First 9 digits of frac(sqrt(17))
  2295. np.random.seed(123105625)
  2296. data = [np.random.normal(size=100) for i in range(4)]
  2297. ax.violinplot(data, positions=range(4), showmeans=0, showextrema=0,
  2298. showmedians=0, points=200)
  2299. @image_comparison(['violinplot_horiz_baseline.png'])
  2300. def test_horiz_violinplot_baseline():
  2301. ax = plt.axes()
  2302. # First 9 digits of frac(sqrt(19))
  2303. np.random.seed(358898943)
  2304. data = [np.random.normal(size=100) for i in range(4)]
  2305. ax.violinplot(data, positions=range(4), vert=False, showmeans=0,
  2306. showextrema=0, showmedians=0)
  2307. @image_comparison(['violinplot_horiz_showmedians.png'])
  2308. def test_horiz_violinplot_showmedians():
  2309. ax = plt.axes()
  2310. # First 9 digits of frac(sqrt(23))
  2311. np.random.seed(795831523)
  2312. data = [np.random.normal(size=100) for i in range(4)]
  2313. ax.violinplot(data, positions=range(4), vert=False, showmeans=0,
  2314. showextrema=0, showmedians=1)
  2315. @image_comparison(['violinplot_horiz_showmeans.png'])
  2316. def test_horiz_violinplot_showmeans():
  2317. ax = plt.axes()
  2318. # First 9 digits of frac(sqrt(29))
  2319. np.random.seed(385164807)
  2320. data = [np.random.normal(size=100) for i in range(4)]
  2321. ax.violinplot(data, positions=range(4), vert=False, showmeans=1,
  2322. showextrema=0, showmedians=0)
  2323. @image_comparison(['violinplot_horiz_showextrema.png'])
  2324. def test_horiz_violinplot_showextrema():
  2325. ax = plt.axes()
  2326. # First 9 digits of frac(sqrt(31))
  2327. np.random.seed(567764362)
  2328. data = [np.random.normal(size=100) for i in range(4)]
  2329. ax.violinplot(data, positions=range(4), vert=False, showmeans=0,
  2330. showextrema=1, showmedians=0)
  2331. @image_comparison(['violinplot_horiz_showall.png'])
  2332. def test_horiz_violinplot_showall():
  2333. ax = plt.axes()
  2334. # First 9 digits of frac(sqrt(37))
  2335. np.random.seed(82762530)
  2336. data = [np.random.normal(size=100) for i in range(4)]
  2337. ax.violinplot(data, positions=range(4), vert=False, showmeans=1,
  2338. showextrema=1, showmedians=1,
  2339. quantiles=[[0.1, 0.9], [0.2, 0.8], [0.3, 0.7], [0.4, 0.6]])
  2340. @image_comparison(['violinplot_horiz_custompoints_10.png'])
  2341. def test_horiz_violinplot_custompoints_10():
  2342. ax = plt.axes()
  2343. # First 9 digits of frac(sqrt(41))
  2344. np.random.seed(403124237)
  2345. data = [np.random.normal(size=100) for i in range(4)]
  2346. ax.violinplot(data, positions=range(4), vert=False, showmeans=0,
  2347. showextrema=0, showmedians=0, points=10)
  2348. @image_comparison(['violinplot_horiz_custompoints_200.png'])
  2349. def test_horiz_violinplot_custompoints_200():
  2350. ax = plt.axes()
  2351. # First 9 digits of frac(sqrt(43))
  2352. np.random.seed(557438524)
  2353. data = [np.random.normal(size=100) for i in range(4)]
  2354. ax.violinplot(data, positions=range(4), vert=False, showmeans=0,
  2355. showextrema=0, showmedians=0, points=200)
  2356. def test_violinplot_bad_positions():
  2357. ax = plt.axes()
  2358. # First 9 digits of frac(sqrt(47))
  2359. np.random.seed(855654600)
  2360. data = [np.random.normal(size=100) for i in range(4)]
  2361. with pytest.raises(ValueError):
  2362. ax.violinplot(data, positions=range(5))
  2363. def test_violinplot_bad_widths():
  2364. ax = plt.axes()
  2365. # First 9 digits of frac(sqrt(53))
  2366. np.random.seed(280109889)
  2367. data = [np.random.normal(size=100) for i in range(4)]
  2368. with pytest.raises(ValueError):
  2369. ax.violinplot(data, positions=range(4), widths=[1, 2, 3])
  2370. def test_violinplot_bad_quantiles():
  2371. ax = plt.axes()
  2372. # First 9 digits of frac(sqrt(73))
  2373. np.random.seed(544003745)
  2374. data = [np.random.normal(size=100)]
  2375. # Different size quantile list and plots
  2376. with pytest.raises(ValueError):
  2377. ax.violinplot(data, quantiles=[[0.1, 0.2], [0.5, 0.7]])
  2378. def test_violinplot_outofrange_quantiles():
  2379. ax = plt.axes()
  2380. # First 9 digits of frac(sqrt(79))
  2381. np.random.seed(888194417)
  2382. data = [np.random.normal(size=100)]
  2383. # Quantile value above 100
  2384. with pytest.raises(ValueError):
  2385. ax.violinplot(data, quantiles=[[0.1, 0.2, 0.3, 1.05]])
  2386. # Quantile value below 0
  2387. with pytest.raises(ValueError):
  2388. ax.violinplot(data, quantiles=[[-0.05, 0.2, 0.3, 0.75]])
  2389. @check_figures_equal(extensions=["png"])
  2390. def test_violinplot_single_list_quantiles(fig_test, fig_ref):
  2391. # Ensures quantile list for 1D can be passed in as single list
  2392. # First 9 digits of frac(sqrt(83))
  2393. np.random.seed(110433579)
  2394. data = [np.random.normal(size=100)]
  2395. # Test image
  2396. ax = fig_test.subplots()
  2397. ax.violinplot(data, quantiles=[0.1, 0.3, 0.9])
  2398. # Reference image
  2399. ax = fig_ref.subplots()
  2400. ax.violinplot(data, quantiles=[[0.1, 0.3, 0.9]])
  2401. @check_figures_equal(extensions=["png"])
  2402. def test_violinplot_pandas_series(fig_test, fig_ref, pd):
  2403. np.random.seed(110433579)
  2404. s1 = pd.Series(np.random.normal(size=7), index=[9, 8, 7, 6, 5, 4, 3])
  2405. s2 = pd.Series(np.random.normal(size=9), index=list('ABCDEFGHI'))
  2406. s3 = pd.Series(np.random.normal(size=11))
  2407. fig_test.subplots().violinplot([s1, s2, s3])
  2408. fig_ref.subplots().violinplot([s1.values, s2.values, s3.values])
  2409. def test_manage_xticks():
  2410. _, ax = plt.subplots()
  2411. ax.set_xlim(0, 4)
  2412. old_xlim = ax.get_xlim()
  2413. np.random.seed(0)
  2414. y1 = np.random.normal(10, 3, 20)
  2415. y2 = np.random.normal(3, 1, 20)
  2416. ax.boxplot([y1, y2], positions=[1, 2], manage_ticks=False)
  2417. new_xlim = ax.get_xlim()
  2418. assert_array_equal(old_xlim, new_xlim)
  2419. def test_boxplot_not_single():
  2420. fig, ax = plt.subplots()
  2421. ax.boxplot(np.random.rand(100), positions=[3])
  2422. ax.boxplot(np.random.rand(100), positions=[5])
  2423. fig.canvas.draw()
  2424. assert ax.get_xlim() == (2.5, 5.5)
  2425. assert list(ax.get_xticks()) == [3, 5]
  2426. assert [t.get_text() for t in ax.get_xticklabels()] == ["3", "5"]
  2427. def test_tick_space_size_0():
  2428. # allow font size to be zero, which affects ticks when there is
  2429. # no other text in the figure.
  2430. plt.plot([0, 1], [0, 1])
  2431. matplotlib.rcParams.update({'font.size': 0})
  2432. b = io.BytesIO()
  2433. plt.savefig(b, dpi=80, format='raw')
  2434. @image_comparison(['errorbar_basic', 'errorbar_mixed', 'errorbar_basic'])
  2435. def test_errorbar():
  2436. x = np.arange(0.1, 4, 0.5)
  2437. y = np.exp(-x)
  2438. yerr = 0.1 + 0.2*np.sqrt(x)
  2439. xerr = 0.1 + yerr
  2440. # First illustrate basic pyplot interface, using defaults where possible.
  2441. fig = plt.figure()
  2442. ax = fig.gca()
  2443. ax.errorbar(x, y, xerr=0.2, yerr=0.4)
  2444. ax.set_title("Simplest errorbars, 0.2 in x, 0.4 in y")
  2445. # Now switch to a more OO interface to exercise more features.
  2446. fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True)
  2447. ax = axs[0, 0]
  2448. ax.errorbar(x, y, yerr=yerr, fmt='o')
  2449. ax.set_title('Vert. symmetric')
  2450. # With 4 subplots, reduce the number of axis ticks to avoid crowding.
  2451. ax.locator_params(nbins=4)
  2452. ax = axs[0, 1]
  2453. ax.errorbar(x, y, xerr=xerr, fmt='o', alpha=0.4)
  2454. ax.set_title('Hor. symmetric w/ alpha')
  2455. ax = axs[1, 0]
  2456. ax.errorbar(x, y, yerr=[yerr, 2*yerr], xerr=[xerr, 2*xerr], fmt='--o')
  2457. ax.set_title('H, V asymmetric')
  2458. ax = axs[1, 1]
  2459. ax.set_yscale('log')
  2460. # Here we have to be careful to keep all y values positive:
  2461. ylower = np.maximum(1e-2, y - yerr)
  2462. yerr_lower = y - ylower
  2463. ax.errorbar(x, y, yerr=[yerr_lower, 2*yerr], xerr=xerr,
  2464. fmt='o', ecolor='g', capthick=2)
  2465. ax.set_title('Mixed sym., log y')
  2466. fig.suptitle('Variable errorbars')
  2467. # Reuse the first testcase from above for a labeled data test
  2468. data = {"x": x, "y": y}
  2469. fig = plt.figure()
  2470. ax = fig.gca()
  2471. ax.errorbar("x", "y", xerr=0.2, yerr=0.4, data=data)
  2472. ax.set_title("Simplest errorbars, 0.2 in x, 0.4 in y")
  2473. def test_errorbar_colorcycle():
  2474. f, ax = plt.subplots()
  2475. x = np.arange(10)
  2476. y = 2*x
  2477. e1, _, _ = ax.errorbar(x, y, c=None)
  2478. e2, _, _ = ax.errorbar(x, 2*y, c=None)
  2479. ln1, = ax.plot(x, 4*y)
  2480. assert mcolors.to_rgba(e1.get_color()) == mcolors.to_rgba('C0')
  2481. assert mcolors.to_rgba(e2.get_color()) == mcolors.to_rgba('C1')
  2482. assert mcolors.to_rgba(ln1.get_color()) == mcolors.to_rgba('C2')
  2483. @check_figures_equal()
  2484. def test_errorbar_cycle_ecolor(fig_test, fig_ref):
  2485. x = np.arange(0.1, 4, 0.5)
  2486. y = [np.exp(-x+n) for n in range(4)]
  2487. axt = fig_test.subplots()
  2488. axr = fig_ref.subplots()
  2489. for yi, color in zip(y, ['C0', 'C1', 'C2', 'C3']):
  2490. axt.errorbar(x, yi, yerr=(yi * 0.25), linestyle='-',
  2491. marker='o', ecolor='black')
  2492. axr.errorbar(x, yi, yerr=(yi * 0.25), linestyle='-',
  2493. marker='o', color=color, ecolor='black')
  2494. def test_errorbar_shape():
  2495. fig = plt.figure()
  2496. ax = fig.gca()
  2497. x = np.arange(0.1, 4, 0.5)
  2498. y = np.exp(-x)
  2499. yerr1 = 0.1 + 0.2*np.sqrt(x)
  2500. yerr = np.vstack((yerr1, 2*yerr1)).T
  2501. xerr = 0.1 + yerr
  2502. with pytest.raises(ValueError):
  2503. ax.errorbar(x, y, yerr=yerr, fmt='o')
  2504. with pytest.raises(ValueError):
  2505. ax.errorbar(x, y, xerr=xerr, fmt='o')
  2506. with pytest.raises(ValueError):
  2507. ax.errorbar(x, y, yerr=yerr, xerr=xerr, fmt='o')
  2508. @image_comparison(['errorbar_limits'])
  2509. def test_errorbar_limits():
  2510. x = np.arange(0.5, 5.5, 0.5)
  2511. y = np.exp(-x)
  2512. xerr = 0.1
  2513. yerr = 0.2
  2514. ls = 'dotted'
  2515. fig = plt.figure()
  2516. ax = fig.add_subplot(1, 1, 1)
  2517. # standard error bars
  2518. plt.errorbar(x, y, xerr=xerr, yerr=yerr, ls=ls, color='blue')
  2519. # including upper limits
  2520. uplims = np.zeros_like(x)
  2521. uplims[[1, 5, 9]] = True
  2522. plt.errorbar(x, y+0.5, xerr=xerr, yerr=yerr, uplims=uplims, ls=ls,
  2523. color='green')
  2524. # including lower limits
  2525. lolims = np.zeros_like(x)
  2526. lolims[[2, 4, 8]] = True
  2527. plt.errorbar(x, y+1.0, xerr=xerr, yerr=yerr, lolims=lolims, ls=ls,
  2528. color='red')
  2529. # including upper and lower limits
  2530. plt.errorbar(x, y+1.5, marker='o', ms=8, xerr=xerr, yerr=yerr,
  2531. lolims=lolims, uplims=uplims, ls=ls, color='magenta')
  2532. # including xlower and xupper limits
  2533. xerr = 0.2
  2534. yerr = np.full_like(x, 0.2)
  2535. yerr[[3, 6]] = 0.3
  2536. xlolims = lolims
  2537. xuplims = uplims
  2538. lolims = np.zeros_like(x)
  2539. uplims = np.zeros_like(x)
  2540. lolims[[6]] = True
  2541. uplims[[3]] = True
  2542. plt.errorbar(x, y+2.1, marker='o', ms=8, xerr=xerr, yerr=yerr,
  2543. xlolims=xlolims, xuplims=xuplims, uplims=uplims,
  2544. lolims=lolims, ls='none', mec='blue', capsize=0,
  2545. color='cyan')
  2546. ax.set_xlim((0, 5.5))
  2547. ax.set_title('Errorbar upper and lower limits')
  2548. def test_errobar_nonefmt():
  2549. # Check that passing 'none' as a format still plots errorbars
  2550. x = np.arange(5)
  2551. y = np.arange(5)
  2552. plotline, _, barlines = plt.errorbar(x, y, xerr=1, yerr=1, fmt='none')
  2553. assert plotline is None
  2554. for errbar in barlines:
  2555. assert np.all(errbar.get_color() == mcolors.to_rgba('C0'))
  2556. @image_comparison(['errorbar_with_prop_cycle.png'],
  2557. style='mpl20', remove_text=True)
  2558. def test_errorbar_with_prop_cycle():
  2559. _cycle = cycler(ls=['--', ':'], marker=['s', 's'], mfc=['k', 'w'])
  2560. plt.rc("axes", prop_cycle=_cycle)
  2561. fig, ax = plt.subplots()
  2562. ax.errorbar(x=[2, 4, 10], y=[3, 2, 4], yerr=0.5)
  2563. ax.errorbar(x=[2, 4, 10], y=[6, 4, 2], yerr=0.5)
  2564. @check_figures_equal()
  2565. def test_errorbar_offsets(fig_test, fig_ref):
  2566. x = np.linspace(0, 1, 15)
  2567. y = x * (1-x)
  2568. yerr = y/6
  2569. ax_ref = fig_ref.subplots()
  2570. ax_test = fig_test.subplots()
  2571. for color, shift in zip('rgbk', [0, 0, 2, 7]):
  2572. y += .02
  2573. # Using feature in question
  2574. ax_test.errorbar(x, y, yerr, errorevery=(shift, 4),
  2575. capsize=4, c=color)
  2576. # Using manual errorbars
  2577. # n.b. errorbar draws the main plot at z=2.1 by default
  2578. ax_ref.plot(x, y, c=color, zorder=2.1)
  2579. ax_ref.errorbar(x[shift::4], y[shift::4], yerr[shift::4],
  2580. capsize=4, c=color, fmt='none')
  2581. @image_comparison(['hist_stacked_stepfilled', 'hist_stacked_stepfilled'])
  2582. def test_hist_stacked_stepfilled():
  2583. # make some data
  2584. d1 = np.linspace(1, 3, 20)
  2585. d2 = np.linspace(0, 10, 50)
  2586. fig = plt.figure()
  2587. ax = fig.add_subplot(111)
  2588. ax.hist((d1, d2), histtype="stepfilled", stacked=True)
  2589. # Reuse testcase from above for a labeled data test
  2590. data = {"x": (d1, d2)}
  2591. fig = plt.figure()
  2592. ax = fig.add_subplot(111)
  2593. ax.hist("x", histtype="stepfilled", stacked=True, data=data)
  2594. @image_comparison(['hist_offset'])
  2595. def test_hist_offset():
  2596. # make some data
  2597. d1 = np.linspace(0, 10, 50)
  2598. d2 = np.linspace(1, 3, 20)
  2599. fig = plt.figure()
  2600. ax = fig.add_subplot(111)
  2601. ax.hist(d1, bottom=5)
  2602. ax.hist(d2, bottom=15)
  2603. @image_comparison(['hist_step.png'], remove_text=True)
  2604. def test_hist_step():
  2605. # make some data
  2606. d1 = np.linspace(1, 3, 20)
  2607. fig = plt.figure()
  2608. ax = fig.add_subplot(111)
  2609. ax.hist(d1, histtype="step")
  2610. ax.set_ylim(0, 10)
  2611. ax.set_xlim(-1, 5)
  2612. @image_comparison(['hist_step_horiz.png'])
  2613. def test_hist_step_horiz():
  2614. # make some data
  2615. d1 = np.linspace(0, 10, 50)
  2616. d2 = np.linspace(1, 3, 20)
  2617. fig = plt.figure()
  2618. ax = fig.add_subplot(111)
  2619. ax.hist((d1, d2), histtype="step", orientation="horizontal")
  2620. @image_comparison(['hist_stacked_weights'])
  2621. def test_hist_stacked_weighted():
  2622. # make some data
  2623. d1 = np.linspace(0, 10, 50)
  2624. d2 = np.linspace(1, 3, 20)
  2625. w1 = np.linspace(0.01, 3.5, 50)
  2626. w2 = np.linspace(0.05, 2., 20)
  2627. fig = plt.figure()
  2628. ax = fig.add_subplot(111)
  2629. ax.hist((d1, d2), weights=(w1, w2), histtype="stepfilled", stacked=True)
  2630. @pytest.mark.parametrize("use_line_collection", [True, False],
  2631. ids=['w/ line collection', 'w/o line collection'])
  2632. @image_comparison(['stem.png'], style='mpl20', remove_text=True)
  2633. def test_stem(use_line_collection):
  2634. x = np.linspace(0.1, 2 * np.pi, 100)
  2635. args = (x, np.cos(x))
  2636. # Label is a single space to force a legend to be drawn, but to avoid any
  2637. # text being drawn
  2638. kwargs = dict(linefmt='C2-.', markerfmt='k+', basefmt='C1-.',
  2639. label=' ', use_line_collection=use_line_collection)
  2640. fig, ax = plt.subplots()
  2641. ax.stem(*args, **kwargs)
  2642. ax.legend()
  2643. def test_stem_args():
  2644. fig = plt.figure()
  2645. ax = fig.add_subplot(1, 1, 1)
  2646. x = list(range(10))
  2647. y = list(range(10))
  2648. # Test the call signatures
  2649. ax.stem(y)
  2650. ax.stem(x, y)
  2651. ax.stem(x, y, 'r--')
  2652. ax.stem(x, y, 'r--', basefmt='b--')
  2653. def test_stem_dates():
  2654. fig, ax = plt.subplots(1, 1)
  2655. xs = [dateutil.parser.parse("2013-9-28 11:00:00"),
  2656. dateutil.parser.parse("2013-9-28 12:00:00")]
  2657. ys = [100, 200]
  2658. ax.stem(xs, ys, "*-")
  2659. @image_comparison(['hist_stacked_stepfilled_alpha'])
  2660. def test_hist_stacked_stepfilled_alpha():
  2661. # make some data
  2662. d1 = np.linspace(1, 3, 20)
  2663. d2 = np.linspace(0, 10, 50)
  2664. fig = plt.figure()
  2665. ax = fig.add_subplot(111)
  2666. ax.hist((d1, d2), histtype="stepfilled", stacked=True, alpha=0.5)
  2667. @image_comparison(['hist_stacked_step'])
  2668. def test_hist_stacked_step():
  2669. # make some data
  2670. d1 = np.linspace(1, 3, 20)
  2671. d2 = np.linspace(0, 10, 50)
  2672. fig = plt.figure()
  2673. ax = fig.add_subplot(111)
  2674. ax.hist((d1, d2), histtype="step", stacked=True)
  2675. @image_comparison(['hist_stacked_normed'])
  2676. def test_hist_stacked_density():
  2677. # make some data
  2678. d1 = np.linspace(1, 3, 20)
  2679. d2 = np.linspace(0, 10, 50)
  2680. fig, ax = plt.subplots()
  2681. ax.hist((d1, d2), stacked=True, density=True)
  2682. @image_comparison(['hist_step_bottom.png'], remove_text=True)
  2683. def test_hist_step_bottom():
  2684. # make some data
  2685. d1 = np.linspace(1, 3, 20)
  2686. fig = plt.figure()
  2687. ax = fig.add_subplot(111)
  2688. ax.hist(d1, bottom=np.arange(10), histtype="stepfilled")
  2689. def test_hist_stepfilled_geometry():
  2690. bins = [0, 1, 2, 3]
  2691. data = [0, 0, 1, 1, 1, 2]
  2692. _, _, (polygon, ) = plt.hist(data,
  2693. bins=bins,
  2694. histtype='stepfilled')
  2695. xy = [[0, 0], [0, 2], [1, 2], [1, 3], [2, 3], [2, 1], [3, 1],
  2696. [3, 0], [2, 0], [2, 0], [1, 0], [1, 0], [0, 0]]
  2697. assert_array_equal(polygon.get_xy(), xy)
  2698. def test_hist_step_geometry():
  2699. bins = [0, 1, 2, 3]
  2700. data = [0, 0, 1, 1, 1, 2]
  2701. _, _, (polygon, ) = plt.hist(data,
  2702. bins=bins,
  2703. histtype='step')
  2704. xy = [[0, 0], [0, 2], [1, 2], [1, 3], [2, 3], [2, 1], [3, 1], [3, 0]]
  2705. assert_array_equal(polygon.get_xy(), xy)
  2706. def test_hist_stepfilled_bottom_geometry():
  2707. bins = [0, 1, 2, 3]
  2708. data = [0, 0, 1, 1, 1, 2]
  2709. _, _, (polygon, ) = plt.hist(data,
  2710. bins=bins,
  2711. bottom=[1, 2, 1.5],
  2712. histtype='stepfilled')
  2713. xy = [[0, 1], [0, 3], [1, 3], [1, 5], [2, 5], [2, 2.5], [3, 2.5],
  2714. [3, 1.5], [2, 1.5], [2, 2], [1, 2], [1, 1], [0, 1]]
  2715. assert_array_equal(polygon.get_xy(), xy)
  2716. def test_hist_step_bottom_geometry():
  2717. bins = [0, 1, 2, 3]
  2718. data = [0, 0, 1, 1, 1, 2]
  2719. _, _, (polygon, ) = plt.hist(data,
  2720. bins=bins,
  2721. bottom=[1, 2, 1.5],
  2722. histtype='step')
  2723. xy = [[0, 1], [0, 3], [1, 3], [1, 5], [2, 5], [2, 2.5], [3, 2.5], [3, 1.5]]
  2724. assert_array_equal(polygon.get_xy(), xy)
  2725. def test_hist_stacked_stepfilled_geometry():
  2726. bins = [0, 1, 2, 3]
  2727. data_1 = [0, 0, 1, 1, 1, 2]
  2728. data_2 = [0, 1, 2]
  2729. _, _, patches = plt.hist([data_1, data_2],
  2730. bins=bins,
  2731. stacked=True,
  2732. histtype='stepfilled')
  2733. assert len(patches) == 2
  2734. polygon, = patches[0]
  2735. xy = [[0, 0], [0, 2], [1, 2], [1, 3], [2, 3], [2, 1], [3, 1],
  2736. [3, 0], [2, 0], [2, 0], [1, 0], [1, 0], [0, 0]]
  2737. assert_array_equal(polygon.get_xy(), xy)
  2738. polygon, = patches[1]
  2739. xy = [[0, 2], [0, 3], [1, 3], [1, 4], [2, 4], [2, 2], [3, 2],
  2740. [3, 1], [2, 1], [2, 3], [1, 3], [1, 2], [0, 2]]
  2741. assert_array_equal(polygon.get_xy(), xy)
  2742. def test_hist_stacked_step_geometry():
  2743. bins = [0, 1, 2, 3]
  2744. data_1 = [0, 0, 1, 1, 1, 2]
  2745. data_2 = [0, 1, 2]
  2746. _, _, patches = plt.hist([data_1, data_2],
  2747. bins=bins,
  2748. stacked=True,
  2749. histtype='step')
  2750. assert len(patches) == 2
  2751. polygon, = patches[0]
  2752. xy = [[0, 0], [0, 2], [1, 2], [1, 3], [2, 3], [2, 1], [3, 1], [3, 0]]
  2753. assert_array_equal(polygon.get_xy(), xy)
  2754. polygon, = patches[1]
  2755. xy = [[0, 2], [0, 3], [1, 3], [1, 4], [2, 4], [2, 2], [3, 2], [3, 1]]
  2756. assert_array_equal(polygon.get_xy(), xy)
  2757. def test_hist_stacked_stepfilled_bottom_geometry():
  2758. bins = [0, 1, 2, 3]
  2759. data_1 = [0, 0, 1, 1, 1, 2]
  2760. data_2 = [0, 1, 2]
  2761. _, _, patches = plt.hist([data_1, data_2],
  2762. bins=bins,
  2763. stacked=True,
  2764. bottom=[1, 2, 1.5],
  2765. histtype='stepfilled')
  2766. assert len(patches) == 2
  2767. polygon, = patches[0]
  2768. xy = [[0, 1], [0, 3], [1, 3], [1, 5], [2, 5], [2, 2.5], [3, 2.5],
  2769. [3, 1.5], [2, 1.5], [2, 2], [1, 2], [1, 1], [0, 1]]
  2770. assert_array_equal(polygon.get_xy(), xy)
  2771. polygon, = patches[1]
  2772. xy = [[0, 3], [0, 4], [1, 4], [1, 6], [2, 6], [2, 3.5], [3, 3.5],
  2773. [3, 2.5], [2, 2.5], [2, 5], [1, 5], [1, 3], [0, 3]]
  2774. assert_array_equal(polygon.get_xy(), xy)
  2775. def test_hist_stacked_step_bottom_geometry():
  2776. bins = [0, 1, 2, 3]
  2777. data_1 = [0, 0, 1, 1, 1, 2]
  2778. data_2 = [0, 1, 2]
  2779. _, _, patches = plt.hist([data_1, data_2],
  2780. bins=bins,
  2781. stacked=True,
  2782. bottom=[1, 2, 1.5],
  2783. histtype='step')
  2784. assert len(patches) == 2
  2785. polygon, = patches[0]
  2786. xy = [[0, 1], [0, 3], [1, 3], [1, 5], [2, 5], [2, 2.5], [3, 2.5], [3, 1.5]]
  2787. assert_array_equal(polygon.get_xy(), xy)
  2788. polygon, = patches[1]
  2789. xy = [[0, 3], [0, 4], [1, 4], [1, 6], [2, 6], [2, 3.5], [3, 3.5], [3, 2.5]]
  2790. assert_array_equal(polygon.get_xy(), xy)
  2791. @image_comparison(['hist_stacked_bar'])
  2792. def test_hist_stacked_bar():
  2793. # make some data
  2794. d = [[100, 100, 100, 100, 200, 320, 450, 80, 20, 600, 310, 800],
  2795. [20, 23, 50, 11, 100, 420], [120, 120, 120, 140, 140, 150, 180],
  2796. [60, 60, 60, 60, 300, 300, 5, 5, 5, 5, 10, 300],
  2797. [555, 555, 555, 30, 30, 30, 30, 30, 100, 100, 100, 100, 30, 30],
  2798. [30, 30, 30, 30, 400, 400, 400, 400, 400, 400, 400, 400]]
  2799. colors = [(0.5759849696758961, 1.0, 0.0), (0.0, 1.0, 0.350624650815206),
  2800. (0.0, 1.0, 0.6549834156005998), (0.0, 0.6569064625276622, 1.0),
  2801. (0.28302699607823545, 0.0, 1.0), (0.6849123462299822, 0.0, 1.0)]
  2802. labels = ['green', 'orange', ' yellow', 'magenta', 'black']
  2803. fig = plt.figure()
  2804. ax = fig.add_subplot(111)
  2805. ax.hist(d, bins=10, histtype='barstacked', align='mid', color=colors,
  2806. label=labels)
  2807. ax.legend(loc='upper right', bbox_to_anchor=(1.0, 1.0), ncol=1)
  2808. def test_hist_emptydata():
  2809. fig = plt.figure()
  2810. ax = fig.add_subplot(111)
  2811. ax.hist([[], range(10), range(10)], histtype="step")
  2812. def test_hist_labels():
  2813. # test singleton labels OK
  2814. fig, ax = plt.subplots()
  2815. l = ax.hist([0, 1], label=0)
  2816. assert l[2][0].get_label() == '0'
  2817. l = ax.hist([0, 1], label=[0])
  2818. assert l[2][0].get_label() == '0'
  2819. l = ax.hist([0, 1], label=None)
  2820. assert l[2][0].get_label() == '_nolegend_'
  2821. l = ax.hist([0, 1], label='0')
  2822. assert l[2][0].get_label() == '0'
  2823. l = ax.hist([0, 1], label='00')
  2824. assert l[2][0].get_label() == '00'
  2825. @image_comparison(['transparent_markers'], remove_text=True)
  2826. def test_transparent_markers():
  2827. np.random.seed(0)
  2828. data = np.random.random(50)
  2829. fig = plt.figure()
  2830. ax = fig.add_subplot(111)
  2831. ax.plot(data, 'D', mfc='none', markersize=100)
  2832. @image_comparison(['rgba_markers'], remove_text=True)
  2833. def test_rgba_markers():
  2834. fig, axs = plt.subplots(ncols=2)
  2835. rcolors = [(1, 0, 0, 1), (1, 0, 0, 0.5)]
  2836. bcolors = [(0, 0, 1, 1), (0, 0, 1, 0.5)]
  2837. alphas = [None, 0.2]
  2838. kw = dict(ms=100, mew=20)
  2839. for i, alpha in enumerate(alphas):
  2840. for j, rcolor in enumerate(rcolors):
  2841. for k, bcolor in enumerate(bcolors):
  2842. axs[i].plot(j+1, k+1, 'o', mfc=bcolor, mec=rcolor,
  2843. alpha=alpha, **kw)
  2844. axs[i].plot(j+1, k+3, 'x', mec=rcolor, alpha=alpha, **kw)
  2845. for ax in axs:
  2846. ax.axis([-1, 4, 0, 5])
  2847. @image_comparison(['mollweide_grid'], remove_text=True)
  2848. def test_mollweide_grid():
  2849. # test that both horizontal and vertical gridlines appear on the Mollweide
  2850. # projection
  2851. fig = plt.figure()
  2852. ax = fig.add_subplot(111, projection='mollweide')
  2853. ax.grid()
  2854. def test_mollweide_forward_inverse_closure():
  2855. # test that the round-trip Mollweide forward->inverse transformation is an
  2856. # approximate identity
  2857. fig = plt.figure()
  2858. ax = fig.add_subplot(111, projection='mollweide')
  2859. # set up 1-degree grid in longitude, latitude
  2860. lon = np.linspace(-np.pi, np.pi, 360)
  2861. lat = np.linspace(-np.pi / 2.0, np.pi / 2.0, 180)
  2862. lon, lat = np.meshgrid(lon, lat)
  2863. ll = np.vstack((lon.flatten(), lat.flatten())).T
  2864. # perform forward transform
  2865. xy = ax.transProjection.transform(ll)
  2866. # perform inverse transform
  2867. ll2 = ax.transProjection.inverted().transform(xy)
  2868. # compare
  2869. np.testing.assert_array_almost_equal(ll, ll2, 3)
  2870. def test_mollweide_inverse_forward_closure():
  2871. # test that the round-trip Mollweide inverse->forward transformation is an
  2872. # approximate identity
  2873. fig = plt.figure()
  2874. ax = fig.add_subplot(111, projection='mollweide')
  2875. # set up grid in x, y
  2876. x = np.linspace(0, 1, 500)
  2877. x, y = np.meshgrid(x, x)
  2878. xy = np.vstack((x.flatten(), y.flatten())).T
  2879. # perform inverse transform
  2880. ll = ax.transProjection.inverted().transform(xy)
  2881. # perform forward transform
  2882. xy2 = ax.transProjection.transform(ll)
  2883. # compare
  2884. np.testing.assert_array_almost_equal(xy, xy2, 3)
  2885. @image_comparison(['test_alpha'], remove_text=True)
  2886. def test_alpha():
  2887. np.random.seed(0)
  2888. data = np.random.random(50)
  2889. fig = plt.figure()
  2890. ax = fig.add_subplot(111)
  2891. # alpha=.5 markers, solid line
  2892. ax.plot(data, '-D', color=[1, 0, 0], mfc=[1, 0, 0, .5],
  2893. markersize=20, lw=10)
  2894. # everything solid by kwarg
  2895. ax.plot(data + 2, '-D', color=[1, 0, 0, .5], mfc=[1, 0, 0, .5],
  2896. markersize=20, lw=10,
  2897. alpha=1)
  2898. # everything alpha=.5 by kwarg
  2899. ax.plot(data + 4, '-D', color=[1, 0, 0], mfc=[1, 0, 0],
  2900. markersize=20, lw=10,
  2901. alpha=.5)
  2902. # everything alpha=.5 by colors
  2903. ax.plot(data + 6, '-D', color=[1, 0, 0, .5], mfc=[1, 0, 0, .5],
  2904. markersize=20, lw=10)
  2905. # alpha=.5 line, solid markers
  2906. ax.plot(data + 8, '-D', color=[1, 0, 0, .5], mfc=[1, 0, 0],
  2907. markersize=20, lw=10)
  2908. @image_comparison(['eventplot', 'eventplot'], remove_text=True)
  2909. def test_eventplot():
  2910. np.random.seed(0)
  2911. data1 = np.random.random([32, 20]).tolist()
  2912. data2 = np.random.random([6, 20]).tolist()
  2913. data = data1 + data2
  2914. num_datasets = len(data)
  2915. colors1 = [[0, 1, .7]] * len(data1)
  2916. colors2 = [[1, 0, 0],
  2917. [0, 1, 0],
  2918. [0, 0, 1],
  2919. [1, .75, 0],
  2920. [1, 0, 1],
  2921. [0, 1, 1]]
  2922. colors = colors1 + colors2
  2923. lineoffsets1 = 12 + np.arange(0, len(data1)) * .33
  2924. lineoffsets2 = [-15, -3, 1, 1.5, 6, 10]
  2925. lineoffsets = lineoffsets1.tolist() + lineoffsets2
  2926. linelengths1 = [.33] * len(data1)
  2927. linelengths2 = [5, 2, 1, 1, 3, 1.5]
  2928. linelengths = linelengths1 + linelengths2
  2929. fig = plt.figure()
  2930. axobj = fig.add_subplot(111)
  2931. colls = axobj.eventplot(data, colors=colors, lineoffsets=lineoffsets,
  2932. linelengths=linelengths)
  2933. num_collections = len(colls)
  2934. assert num_collections == num_datasets
  2935. # Reuse testcase from above for a labeled data test
  2936. data = {"pos": data, "c": colors, "lo": lineoffsets, "ll": linelengths}
  2937. fig = plt.figure()
  2938. axobj = fig.add_subplot(111)
  2939. colls = axobj.eventplot("pos", colors="c", lineoffsets="lo",
  2940. linelengths="ll", data=data)
  2941. num_collections = len(colls)
  2942. assert num_collections == num_datasets
  2943. @image_comparison(['test_eventplot_defaults.png'], remove_text=True)
  2944. def test_eventplot_defaults():
  2945. """
  2946. test that eventplot produces the correct output given the default params
  2947. (see bug #3728)
  2948. """
  2949. np.random.seed(0)
  2950. data1 = np.random.random([32, 20]).tolist()
  2951. data2 = np.random.random([6, 20]).tolist()
  2952. data = data1 + data2
  2953. fig = plt.figure()
  2954. axobj = fig.add_subplot(111)
  2955. axobj.eventplot(data)
  2956. @pytest.mark.parametrize(('colors'), [
  2957. ('0.5',), # string color with multiple characters: not OK before #8193 fix
  2958. ('tab:orange', 'tab:pink', 'tab:cyan', 'bLacK'), # case-insensitive
  2959. ('red', (0, 1, 0), None, (1, 0, 1, 0.5)), # a tricky case mixing types
  2960. ])
  2961. def test_eventplot_colors(colors):
  2962. """Test the *colors* parameter of eventplot. Inspired by issue #8193."""
  2963. data = [[i] for i in range(4)] # 4 successive events of different nature
  2964. # Build the list of the expected colors
  2965. expected = [c if c is not None else 'C0' for c in colors]
  2966. # Convert the list into an array of RGBA values
  2967. # NB: ['rgbk'] is not a valid argument for to_rgba_array, while 'rgbk' is.
  2968. if len(expected) == 1:
  2969. expected = expected[0]
  2970. expected = np.broadcast_to(mcolors.to_rgba_array(expected), (len(data), 4))
  2971. fig, ax = plt.subplots()
  2972. if len(colors) == 1: # tuple with a single string (like '0.5' or 'rgbk')
  2973. colors = colors[0]
  2974. collections = ax.eventplot(data, colors=colors)
  2975. for coll, color in zip(collections, expected):
  2976. assert_allclose(coll.get_color(), color)
  2977. @image_comparison(['test_eventplot_problem_kwargs.png'], remove_text=True)
  2978. def test_eventplot_problem_kwargs(recwarn):
  2979. """
  2980. test that 'singular' versions of LineCollection props raise an
  2981. IgnoredKeywordWarning rather than overriding the 'plural' versions (e.g.
  2982. to prevent 'color' from overriding 'colors', see issue #4297)
  2983. """
  2984. np.random.seed(0)
  2985. data1 = np.random.random([20]).tolist()
  2986. data2 = np.random.random([10]).tolist()
  2987. data = [data1, data2]
  2988. fig = plt.figure()
  2989. axobj = fig.add_subplot(111)
  2990. axobj.eventplot(data,
  2991. colors=['r', 'b'],
  2992. color=['c', 'm'],
  2993. linewidths=[2, 1],
  2994. linewidth=[1, 2],
  2995. linestyles=['solid', 'dashed'],
  2996. linestyle=['dashdot', 'dotted'])
  2997. # check that three IgnoredKeywordWarnings were raised
  2998. assert len(recwarn) == 3
  2999. assert all(issubclass(wi.category, MatplotlibDeprecationWarning)
  3000. for wi in recwarn)
  3001. def test_empty_eventplot():
  3002. fig, ax = plt.subplots(1, 1)
  3003. ax.eventplot([[]], colors=[(0.0, 0.0, 0.0, 0.0)])
  3004. plt.draw()
  3005. @pytest.mark.parametrize('data', [[[]], [[], [0, 1]], [[0, 1], []]])
  3006. @pytest.mark.parametrize(
  3007. 'orientation', ['_empty', 'vertical', 'horizontal', None, 'none'])
  3008. def test_eventplot_orientation(data, orientation):
  3009. """Introduced when fixing issue #6412."""
  3010. opts = {} if orientation == "_empty" else {'orientation': orientation}
  3011. fig, ax = plt.subplots(1, 1)
  3012. with (pytest.warns(MatplotlibDeprecationWarning)
  3013. if orientation in [None, 'none'] else nullcontext()):
  3014. ax.eventplot(data, **opts)
  3015. plt.draw()
  3016. @image_comparison(['marker_styles.png'], remove_text=True)
  3017. def test_marker_styles():
  3018. fig = plt.figure()
  3019. ax = fig.add_subplot(111)
  3020. for y, marker in enumerate(sorted(matplotlib.markers.MarkerStyle.markers,
  3021. key=lambda x: str(type(x))+str(x))):
  3022. ax.plot((y % 2)*5 + np.arange(10)*10, np.ones(10)*10*y, linestyle='',
  3023. marker=marker, markersize=10+y/5, label=marker)
  3024. @image_comparison(['rc_markerfill.png'])
  3025. def test_markers_fillstyle_rcparams():
  3026. fig, ax = plt.subplots()
  3027. x = np.arange(7)
  3028. for idx, (style, marker) in enumerate(
  3029. [('top', 's'), ('bottom', 'o'), ('none', '^')]):
  3030. matplotlib.rcParams['markers.fillstyle'] = style
  3031. ax.plot(x+idx, marker=marker)
  3032. @image_comparison(['vertex_markers.png'], remove_text=True)
  3033. def test_vertex_markers():
  3034. data = list(range(10))
  3035. marker_as_tuple = ((-1, -1), (1, -1), (1, 1), (-1, 1))
  3036. marker_as_list = [(-1, -1), (1, -1), (1, 1), (-1, 1)]
  3037. fig = plt.figure()
  3038. ax = fig.add_subplot(111)
  3039. ax.plot(data, linestyle='', marker=marker_as_tuple, mfc='k')
  3040. ax.plot(data[::-1], linestyle='', marker=marker_as_list, mfc='b')
  3041. ax.set_xlim([-1, 10])
  3042. ax.set_ylim([-1, 10])
  3043. @image_comparison(['vline_hline_zorder', 'errorbar_zorder'],
  3044. tol=0 if platform.machine() == 'x86_64' else 0.02)
  3045. def test_eb_line_zorder():
  3046. x = list(range(10))
  3047. # First illustrate basic pyplot interface, using defaults where possible.
  3048. fig = plt.figure()
  3049. ax = fig.gca()
  3050. ax.plot(x, lw=10, zorder=5)
  3051. ax.axhline(1, color='red', lw=10, zorder=1)
  3052. ax.axhline(5, color='green', lw=10, zorder=10)
  3053. ax.axvline(7, color='m', lw=10, zorder=7)
  3054. ax.axvline(2, color='k', lw=10, zorder=3)
  3055. ax.set_title("axvline and axhline zorder test")
  3056. # Now switch to a more OO interface to exercise more features.
  3057. fig = plt.figure()
  3058. ax = fig.gca()
  3059. x = list(range(10))
  3060. y = np.zeros(10)
  3061. yerr = list(range(10))
  3062. ax.errorbar(x, y, yerr=yerr, zorder=5, lw=5, color='r')
  3063. for j in range(10):
  3064. ax.axhline(j, lw=5, color='k', zorder=j)
  3065. ax.axhline(-j, lw=5, color='k', zorder=j)
  3066. ax.set_title("errorbar zorder test")
  3067. @check_figures_equal()
  3068. def test_axline(fig_test, fig_ref):
  3069. ax = fig_test.subplots()
  3070. ax.set(xlim=(-1, 1), ylim=(-1, 1))
  3071. ax.axline((0, 0), (1, 1))
  3072. ax.axline((0, 0), (1, 0), color='C1')
  3073. ax.axline((0, 0.5), (1, 0.5), color='C2')
  3074. # slopes
  3075. ax.axline((-0.7, -0.5), slope=0, color='C3')
  3076. ax.axline((1, -0.5), slope=-0.5, color='C4')
  3077. ax.axline((-0.5, 1), slope=float('inf'), color='C5')
  3078. ax = fig_ref.subplots()
  3079. ax.set(xlim=(-1, 1), ylim=(-1, 1))
  3080. ax.plot([-1, 1], [-1, 1])
  3081. ax.axhline(0, color='C1')
  3082. ax.axhline(0.5, color='C2')
  3083. # slopes
  3084. ax.axhline(-0.5, color='C3')
  3085. ax.plot([-1, 1], [0.5, -0.5], color='C4')
  3086. ax.axvline(-0.5, color='C5')
  3087. def test_axline_args():
  3088. """Exactly one of *xy2* and *slope* must be specified."""
  3089. fig, ax = plt.subplots()
  3090. with pytest.raises(TypeError):
  3091. ax.axline((0, 0)) # missing second parameter
  3092. with pytest.raises(TypeError):
  3093. ax.axline((0, 0), (1, 1), slope=1) # redundant parameters
  3094. ax.set_xscale('log')
  3095. with pytest.raises(TypeError):
  3096. ax.axline((0, 0), slope=1)
  3097. ax.set_xscale('linear')
  3098. ax.set_yscale('log')
  3099. with pytest.raises(TypeError):
  3100. ax.axline((0, 0), slope=1)
  3101. @image_comparison(['vlines_basic', 'vlines_with_nan', 'vlines_masked'],
  3102. extensions=['png'])
  3103. def test_vlines():
  3104. # normal
  3105. x1 = [2, 3, 4, 5, 7]
  3106. y1 = [2, -6, 3, 8, 2]
  3107. fig1, ax1 = plt.subplots()
  3108. ax1.vlines(x1, 0, y1, colors='g', linewidth=5)
  3109. # GH #7406
  3110. x2 = [2, 3, 4, 5, 6, 7]
  3111. y2 = [2, -6, 3, 8, np.nan, 2]
  3112. fig2, (ax2, ax3, ax4) = plt.subplots(nrows=3, figsize=(4, 8))
  3113. ax2.vlines(x2, 0, y2, colors='g', linewidth=5)
  3114. x3 = [2, 3, 4, 5, 6, 7]
  3115. y3 = [np.nan, 2, -6, 3, 8, 2]
  3116. ax3.vlines(x3, 0, y3, colors='r', linewidth=3, linestyle='--')
  3117. x4 = [2, 3, 4, 5, 6, 7]
  3118. y4 = [np.nan, 2, -6, 3, 8, np.nan]
  3119. ax4.vlines(x4, 0, y4, colors='k', linewidth=2)
  3120. # tweak the x-axis so we can see the lines better
  3121. for ax in [ax1, ax2, ax3, ax4]:
  3122. ax.set_xlim(0, 10)
  3123. # check that the y-lims are all automatically the same
  3124. assert ax1.get_ylim() == ax2.get_ylim()
  3125. assert ax1.get_ylim() == ax3.get_ylim()
  3126. assert ax1.get_ylim() == ax4.get_ylim()
  3127. fig3, ax5 = plt.subplots()
  3128. x5 = np.ma.masked_equal([2, 4, 6, 8, 10, 12], 8)
  3129. ymin5 = np.ma.masked_equal([0, 1, -1, 0, 2, 1], 2)
  3130. ymax5 = np.ma.masked_equal([13, 14, 15, 16, 17, 18], 18)
  3131. ax5.vlines(x5, ymin5, ymax5, colors='k', linewidth=2)
  3132. ax5.set_xlim(0, 15)
  3133. def test_vlines_default():
  3134. fig, ax = plt.subplots()
  3135. with mpl.rc_context({'lines.color': 'red'}):
  3136. lines = ax.vlines(0.5, 0, 1)
  3137. assert mpl.colors.same_color(lines.get_color(), 'red')
  3138. @image_comparison(['hlines_basic', 'hlines_with_nan', 'hlines_masked'],
  3139. extensions=['png'])
  3140. def test_hlines():
  3141. # normal
  3142. y1 = [2, 3, 4, 5, 7]
  3143. x1 = [2, -6, 3, 8, 2]
  3144. fig1, ax1 = plt.subplots()
  3145. ax1.hlines(y1, 0, x1, colors='g', linewidth=5)
  3146. # GH #7406
  3147. y2 = [2, 3, 4, 5, 6, 7]
  3148. x2 = [2, -6, 3, 8, np.nan, 2]
  3149. fig2, (ax2, ax3, ax4) = plt.subplots(nrows=3, figsize=(4, 8))
  3150. ax2.hlines(y2, 0, x2, colors='g', linewidth=5)
  3151. y3 = [2, 3, 4, 5, 6, 7]
  3152. x3 = [np.nan, 2, -6, 3, 8, 2]
  3153. ax3.hlines(y3, 0, x3, colors='r', linewidth=3, linestyle='--')
  3154. y4 = [2, 3, 4, 5, 6, 7]
  3155. x4 = [np.nan, 2, -6, 3, 8, np.nan]
  3156. ax4.hlines(y4, 0, x4, colors='k', linewidth=2)
  3157. # tweak the y-axis so we can see the lines better
  3158. for ax in [ax1, ax2, ax3, ax4]:
  3159. ax.set_ylim(0, 10)
  3160. # check that the x-lims are all automatically the same
  3161. assert ax1.get_xlim() == ax2.get_xlim()
  3162. assert ax1.get_xlim() == ax3.get_xlim()
  3163. assert ax1.get_xlim() == ax4.get_xlim()
  3164. fig3, ax5 = plt.subplots()
  3165. y5 = np.ma.masked_equal([2, 4, 6, 8, 10, 12], 8)
  3166. xmin5 = np.ma.masked_equal([0, 1, -1, 0, 2, 1], 2)
  3167. xmax5 = np.ma.masked_equal([13, 14, 15, 16, 17, 18], 18)
  3168. ax5.hlines(y5, xmin5, xmax5, colors='k', linewidth=2)
  3169. ax5.set_ylim(0, 15)
  3170. def test_hlines_default():
  3171. fig, ax = plt.subplots()
  3172. with mpl.rc_context({'lines.color': 'red'}):
  3173. lines = ax.hlines(0.5, 0, 1)
  3174. assert mpl.colors.same_color(lines.get_color(), 'red')
  3175. @pytest.mark.parametrize('data', [[1, 2, 3, np.nan, 5],
  3176. np.ma.masked_equal([1, 2, 3, 4, 5], 4)])
  3177. @check_figures_equal(extensions=["png"])
  3178. def test_lines_with_colors(fig_test, fig_ref, data):
  3179. test_colors = ['red', 'green', 'blue', 'purple', 'orange']
  3180. fig_test.add_subplot(2, 1, 1).vlines(data, 0, 1,
  3181. colors=test_colors, linewidth=5)
  3182. fig_test.add_subplot(2, 1, 2).hlines(data, 0, 1,
  3183. colors=test_colors, linewidth=5)
  3184. expect_xy = [1, 2, 3, 5]
  3185. expect_color = ['red', 'green', 'blue', 'orange']
  3186. fig_ref.add_subplot(2, 1, 1).vlines(expect_xy, 0, 1,
  3187. colors=expect_color, linewidth=5)
  3188. fig_ref.add_subplot(2, 1, 2).hlines(expect_xy, 0, 1,
  3189. colors=expect_color, linewidth=5)
  3190. @image_comparison(['step_linestyle', 'step_linestyle'], remove_text=True)
  3191. def test_step_linestyle():
  3192. x = y = np.arange(10)
  3193. # First illustrate basic pyplot interface, using defaults where possible.
  3194. fig, ax_lst = plt.subplots(2, 2)
  3195. ax_lst = ax_lst.flatten()
  3196. ln_styles = ['-', '--', '-.', ':']
  3197. for ax, ls in zip(ax_lst, ln_styles):
  3198. ax.step(x, y, lw=5, linestyle=ls, where='pre')
  3199. ax.step(x, y + 1, lw=5, linestyle=ls, where='mid')
  3200. ax.step(x, y + 2, lw=5, linestyle=ls, where='post')
  3201. ax.set_xlim([-1, 5])
  3202. ax.set_ylim([-1, 7])
  3203. # Reuse testcase from above for a labeled data test
  3204. data = {"X": x, "Y0": y, "Y1": y+1, "Y2": y+2}
  3205. fig, ax_lst = plt.subplots(2, 2)
  3206. ax_lst = ax_lst.flatten()
  3207. ln_styles = ['-', '--', '-.', ':']
  3208. for ax, ls in zip(ax_lst, ln_styles):
  3209. ax.step("X", "Y0", lw=5, linestyle=ls, where='pre', data=data)
  3210. ax.step("X", "Y1", lw=5, linestyle=ls, where='mid', data=data)
  3211. ax.step("X", "Y2", lw=5, linestyle=ls, where='post', data=data)
  3212. ax.set_xlim([-1, 5])
  3213. ax.set_ylim([-1, 7])
  3214. @image_comparison(['mixed_collection'], remove_text=True)
  3215. def test_mixed_collection():
  3216. # First illustrate basic pyplot interface, using defaults where possible.
  3217. fig = plt.figure()
  3218. ax = fig.add_subplot(1, 1, 1)
  3219. c = mpatches.Circle((8, 8), radius=4, facecolor='none', edgecolor='green')
  3220. # PDF can optimize this one
  3221. p1 = mpl.collections.PatchCollection([c], match_original=True)
  3222. p1.set_offsets([[0, 0], [24, 24]])
  3223. p1.set_linewidths([1, 5])
  3224. # PDF can't optimize this one, because the alpha of the edge changes
  3225. p2 = mpl.collections.PatchCollection([c], match_original=True)
  3226. p2.set_offsets([[48, 0], [-32, -16]])
  3227. p2.set_linewidths([1, 5])
  3228. p2.set_edgecolors([[0, 0, 0.1, 1.0], [0, 0, 0.1, 0.5]])
  3229. ax.patch.set_color('0.5')
  3230. ax.add_collection(p1)
  3231. ax.add_collection(p2)
  3232. ax.set_xlim(0, 16)
  3233. ax.set_ylim(0, 16)
  3234. def test_subplot_key_hash():
  3235. ax = plt.subplot(np.int32(5), np.int64(1), 1)
  3236. ax.twinx()
  3237. assert ax.get_subplotspec().get_geometry() == (5, 1, 0, 0)
  3238. @image_comparison(
  3239. ["specgram_freqs.png", "specgram_freqs_linear.png",
  3240. "specgram_noise.png", "specgram_noise_linear.png"],
  3241. remove_text=True, tol=0.07, style="default")
  3242. def test_specgram():
  3243. """Test axes.specgram in default (psd) mode."""
  3244. # use former defaults to match existing baseline image
  3245. matplotlib.rcParams['image.interpolation'] = 'nearest'
  3246. n = 1000
  3247. Fs = 10.
  3248. fstims = [[Fs/4, Fs/5, Fs/11], [Fs/4.7, Fs/5.6, Fs/11.9]]
  3249. NFFT_freqs = int(10 * Fs / np.min(fstims))
  3250. x = np.arange(0, n, 1/Fs)
  3251. y_freqs = np.concatenate(
  3252. np.sin(2 * np.pi * np.multiply.outer(fstims, x)).sum(axis=1))
  3253. NFFT_noise = int(10 * Fs / 11)
  3254. np.random.seed(0)
  3255. y_noise = np.concatenate([np.random.standard_normal(n), np.random.rand(n)])
  3256. all_sides = ["default", "onesided", "twosided"]
  3257. for y, NFFT in [(y_freqs, NFFT_freqs), (y_noise, NFFT_noise)]:
  3258. noverlap = NFFT // 2
  3259. pad_to = int(2 ** np.ceil(np.log2(NFFT)))
  3260. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3261. ax.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap,
  3262. pad_to=pad_to, sides=sides)
  3263. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3264. ax.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap,
  3265. pad_to=pad_to, sides=sides,
  3266. scale="linear", norm=matplotlib.colors.LogNorm())
  3267. @image_comparison(
  3268. ["specgram_magnitude_freqs.png", "specgram_magnitude_freqs_linear.png",
  3269. "specgram_magnitude_noise.png", "specgram_magnitude_noise_linear.png"],
  3270. remove_text=True, tol=0.07, style="default")
  3271. def test_specgram_magnitude():
  3272. """Test axes.specgram in magnitude mode."""
  3273. # use former defaults to match existing baseline image
  3274. matplotlib.rcParams['image.interpolation'] = 'nearest'
  3275. n = 1000
  3276. Fs = 10.
  3277. fstims = [[Fs/4, Fs/5, Fs/11], [Fs/4.7, Fs/5.6, Fs/11.9]]
  3278. NFFT_freqs = int(100 * Fs / np.min(fstims))
  3279. x = np.arange(0, n, 1/Fs)
  3280. y = np.sin(2 * np.pi * np.multiply.outer(fstims, x)).sum(axis=1)
  3281. y[:, -1] = 1
  3282. y_freqs = np.hstack(y)
  3283. NFFT_noise = int(10 * Fs / 11)
  3284. np.random.seed(0)
  3285. y_noise = np.concatenate([np.random.standard_normal(n), np.random.rand(n)])
  3286. all_sides = ["default", "onesided", "twosided"]
  3287. for y, NFFT in [(y_freqs, NFFT_freqs), (y_noise, NFFT_noise)]:
  3288. noverlap = NFFT // 2
  3289. pad_to = int(2 ** np.ceil(np.log2(NFFT)))
  3290. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3291. ax.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap,
  3292. pad_to=pad_to, sides=sides, mode="magnitude")
  3293. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3294. ax.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap,
  3295. pad_to=pad_to, sides=sides, mode="magnitude",
  3296. scale="linear", norm=matplotlib.colors.LogNorm())
  3297. @image_comparison(
  3298. ["specgram_angle_freqs.png", "specgram_phase_freqs.png",
  3299. "specgram_angle_noise.png", "specgram_phase_noise.png"],
  3300. remove_text=True, tol=0.07, style="default")
  3301. def test_specgram_angle():
  3302. """Test axes.specgram in angle and phase modes."""
  3303. # use former defaults to match existing baseline image
  3304. matplotlib.rcParams['image.interpolation'] = 'nearest'
  3305. n = 1000
  3306. Fs = 10.
  3307. fstims = [[Fs/4, Fs/5, Fs/11], [Fs/4.7, Fs/5.6, Fs/11.9]]
  3308. NFFT_freqs = int(10 * Fs / np.min(fstims))
  3309. x = np.arange(0, n, 1/Fs)
  3310. y = np.sin(2 * np.pi * np.multiply.outer(fstims, x)).sum(axis=1)
  3311. y[:, -1] = 1
  3312. y_freqs = np.hstack(y)
  3313. NFFT_noise = int(10 * Fs / 11)
  3314. np.random.seed(0)
  3315. y_noise = np.concatenate([np.random.standard_normal(n), np.random.rand(n)])
  3316. all_sides = ["default", "onesided", "twosided"]
  3317. for y, NFFT in [(y_freqs, NFFT_freqs), (y_noise, NFFT_noise)]:
  3318. noverlap = NFFT // 2
  3319. pad_to = int(2 ** np.ceil(np.log2(NFFT)))
  3320. for mode in ["angle", "phase"]:
  3321. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3322. ax.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap,
  3323. pad_to=pad_to, sides=sides, mode=mode)
  3324. with pytest.raises(ValueError):
  3325. ax.specgram(y, NFFT=NFFT, Fs=Fs, noverlap=noverlap,
  3326. pad_to=pad_to, sides=sides, mode=mode,
  3327. scale="dB")
  3328. def test_specgram_fs_none():
  3329. """Test axes.specgram when Fs is None, should not throw error."""
  3330. spec, freqs, t, im = plt.specgram(np.ones(300), Fs=None)
  3331. xmin, xmax, freq0, freq1 = im.get_extent()
  3332. assert xmin == 32 and xmax == 96
  3333. @image_comparison(
  3334. ["psd_freqs.png", "csd_freqs.png", "psd_noise.png", "csd_noise.png"],
  3335. remove_text=True, tol=0.002)
  3336. def test_psd_csd():
  3337. n = 10000
  3338. Fs = 100.
  3339. fstims = [[Fs/4, Fs/5, Fs/11], [Fs/4.7, Fs/5.6, Fs/11.9]]
  3340. NFFT_freqs = int(1000 * Fs / np.min(fstims))
  3341. x = np.arange(0, n, 1/Fs)
  3342. ys_freqs = np.sin(2 * np.pi * np.multiply.outer(fstims, x)).sum(axis=1)
  3343. NFFT_noise = int(1000 * Fs / 11)
  3344. np.random.seed(0)
  3345. ys_noise = [np.random.standard_normal(n), np.random.rand(n)]
  3346. all_kwargs = [{"sides": "default"},
  3347. {"sides": "onesided", "return_line": False},
  3348. {"sides": "twosided", "return_line": True}]
  3349. for ys, NFFT in [(ys_freqs, NFFT_freqs), (ys_noise, NFFT_noise)]:
  3350. noverlap = NFFT // 2
  3351. pad_to = int(2 ** np.ceil(np.log2(NFFT)))
  3352. for ax, kwargs in zip(plt.figure().subplots(3), all_kwargs):
  3353. ret = ax.psd(np.concatenate(ys), NFFT=NFFT, Fs=Fs,
  3354. noverlap=noverlap, pad_to=pad_to, **kwargs)
  3355. assert len(ret) == 2 + kwargs.get("return_line", False)
  3356. ax.set(xlabel="", ylabel="")
  3357. for ax, kwargs in zip(plt.figure().subplots(3), all_kwargs):
  3358. ret = ax.csd(*ys, NFFT=NFFT, Fs=Fs,
  3359. noverlap=noverlap, pad_to=pad_to, **kwargs)
  3360. assert len(ret) == 2 + kwargs.get("return_line", False)
  3361. ax.set(xlabel="", ylabel="")
  3362. @image_comparison(
  3363. ["magnitude_spectrum_freqs_linear.png",
  3364. "magnitude_spectrum_freqs_dB.png",
  3365. "angle_spectrum_freqs.png",
  3366. "phase_spectrum_freqs.png",
  3367. "magnitude_spectrum_noise_linear.png",
  3368. "magnitude_spectrum_noise_dB.png",
  3369. "angle_spectrum_noise.png",
  3370. "phase_spectrum_noise.png"],
  3371. remove_text=True)
  3372. def test_spectrum():
  3373. n = 10000
  3374. Fs = 100.
  3375. fstims1 = [Fs/4, Fs/5, Fs/11]
  3376. NFFT = int(1000 * Fs / min(fstims1))
  3377. pad_to = int(2 ** np.ceil(np.log2(NFFT)))
  3378. x = np.arange(0, n, 1/Fs)
  3379. y_freqs = ((np.sin(2 * np.pi * np.outer(x, fstims1)) * 10**np.arange(3))
  3380. .sum(axis=1))
  3381. np.random.seed(0)
  3382. y_noise = np.hstack([np.random.standard_normal(n), np.random.rand(n)]) - .5
  3383. all_sides = ["default", "onesided", "twosided"]
  3384. kwargs = {"Fs": Fs, "pad_to": pad_to}
  3385. for y in [y_freqs, y_noise]:
  3386. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3387. spec, freqs, line = ax.magnitude_spectrum(y, sides=sides, **kwargs)
  3388. ax.set(xlabel="", ylabel="")
  3389. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3390. spec, freqs, line = ax.magnitude_spectrum(y, sides=sides, **kwargs,
  3391. scale="dB")
  3392. ax.set(xlabel="", ylabel="")
  3393. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3394. spec, freqs, line = ax.angle_spectrum(y, sides=sides, **kwargs)
  3395. ax.set(xlabel="", ylabel="")
  3396. for ax, sides in zip(plt.figure().subplots(3), all_sides):
  3397. spec, freqs, line = ax.phase_spectrum(y, sides=sides, **kwargs)
  3398. ax.set(xlabel="", ylabel="")
  3399. @image_comparison(['twin_spines.png'], remove_text=True)
  3400. def test_twin_spines():
  3401. def make_patch_spines_invisible(ax):
  3402. ax.set_frame_on(True)
  3403. ax.patch.set_visible(False)
  3404. for sp in ax.spines.values():
  3405. sp.set_visible(False)
  3406. fig = plt.figure(figsize=(4, 3))
  3407. fig.subplots_adjust(right=0.75)
  3408. host = fig.add_subplot(111)
  3409. par1 = host.twinx()
  3410. par2 = host.twinx()
  3411. # Offset the right spine of par2. The ticks and label have already been
  3412. # placed on the right by twinx above.
  3413. par2.spines["right"].set_position(("axes", 1.2))
  3414. # Having been created by twinx, par2 has its frame off, so the line of
  3415. # its detached spine is invisible. First, activate the frame but make
  3416. # the patch and spines invisible.
  3417. make_patch_spines_invisible(par2)
  3418. # Second, show the right spine.
  3419. par2.spines["right"].set_visible(True)
  3420. p1, = host.plot([0, 1, 2], [0, 1, 2], "b-")
  3421. p2, = par1.plot([0, 1, 2], [0, 3, 2], "r-")
  3422. p3, = par2.plot([0, 1, 2], [50, 30, 15], "g-")
  3423. host.set_xlim(0, 2)
  3424. host.set_ylim(0, 2)
  3425. par1.set_ylim(0, 4)
  3426. par2.set_ylim(1, 65)
  3427. host.yaxis.label.set_color(p1.get_color())
  3428. par1.yaxis.label.set_color(p2.get_color())
  3429. par2.yaxis.label.set_color(p3.get_color())
  3430. tkw = dict(size=4, width=1.5)
  3431. host.tick_params(axis='y', colors=p1.get_color(), **tkw)
  3432. par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
  3433. par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
  3434. host.tick_params(axis='x', **tkw)
  3435. @image_comparison(['twin_spines_on_top.png', 'twin_spines_on_top.png'],
  3436. remove_text=True)
  3437. def test_twin_spines_on_top():
  3438. matplotlib.rcParams['axes.linewidth'] = 48.0
  3439. matplotlib.rcParams['lines.linewidth'] = 48.0
  3440. fig = plt.figure()
  3441. ax1 = fig.add_subplot(1, 1, 1)
  3442. data = np.array([[1000, 1100, 1200, 1250],
  3443. [310, 301, 360, 400]])
  3444. ax2 = ax1.twinx()
  3445. ax1.plot(data[0], data[1]/1E3, color='#BEAED4')
  3446. ax1.fill_between(data[0], data[1]/1E3, color='#BEAED4', alpha=.8)
  3447. ax2.plot(data[0], data[1]/1E3, color='#7FC97F')
  3448. ax2.fill_between(data[0], data[1]/1E3, color='#7FC97F', alpha=.5)
  3449. # Reuse testcase from above for a labeled data test
  3450. data = {"i": data[0], "j": data[1]/1E3}
  3451. fig = plt.figure()
  3452. ax1 = fig.add_subplot(1, 1, 1)
  3453. ax2 = ax1.twinx()
  3454. ax1.plot("i", "j", color='#BEAED4', data=data)
  3455. ax1.fill_between("i", "j", color='#BEAED4', alpha=.8, data=data)
  3456. ax2.plot("i", "j", color='#7FC97F', data=data)
  3457. ax2.fill_between("i", "j", color='#7FC97F', alpha=.5, data=data)
  3458. @pytest.mark.parametrize("grid_which, major_visible, minor_visible", [
  3459. ("both", True, True),
  3460. ("major", True, False),
  3461. ("minor", False, True),
  3462. ])
  3463. def test_rcparam_grid_minor(grid_which, major_visible, minor_visible):
  3464. mpl.rcParams.update({"axes.grid": True, "axes.grid.which": grid_which})
  3465. fig, ax = plt.subplots()
  3466. fig.canvas.draw()
  3467. assert all(tick.gridline.get_visible() == major_visible
  3468. for tick in ax.xaxis.majorTicks)
  3469. assert all(tick.gridline.get_visible() == minor_visible
  3470. for tick in ax.xaxis.minorTicks)
  3471. def test_grid():
  3472. fig, ax = plt.subplots()
  3473. ax.grid()
  3474. fig.canvas.draw()
  3475. assert ax.xaxis.majorTicks[0].gridline.get_visible()
  3476. ax.grid(visible=False)
  3477. fig.canvas.draw()
  3478. assert not ax.xaxis.majorTicks[0].gridline.get_visible()
  3479. ax.grid(visible=True)
  3480. fig.canvas.draw()
  3481. assert ax.xaxis.majorTicks[0].gridline.get_visible()
  3482. ax.grid()
  3483. fig.canvas.draw()
  3484. assert not ax.xaxis.majorTicks[0].gridline.get_visible()
  3485. def test_vline_limit():
  3486. fig = plt.figure()
  3487. ax = fig.gca()
  3488. ax.axvline(0.5)
  3489. ax.plot([-0.1, 0, 0.2, 0.1])
  3490. (ymin, ymax) = ax.get_ylim()
  3491. assert_allclose(ax.get_ylim(), (-.1, .2))
  3492. def test_empty_shared_subplots():
  3493. # empty plots with shared axes inherit limits from populated plots
  3494. fig, axs = plt.subplots(nrows=1, ncols=2, sharex=True, sharey=True)
  3495. axs[0].plot([1, 2, 3], [2, 4, 6])
  3496. x0, x1 = axs[1].get_xlim()
  3497. y0, y1 = axs[1].get_ylim()
  3498. assert x0 <= 1
  3499. assert x1 >= 3
  3500. assert y0 <= 2
  3501. assert y1 >= 6
  3502. def test_shared_with_aspect_1():
  3503. # allow sharing one axis
  3504. for adjustable in ['box', 'datalim']:
  3505. fig, axs = plt.subplots(nrows=2, sharex=True)
  3506. axs[0].set_aspect(2, adjustable=adjustable, share=True)
  3507. assert axs[1].get_aspect() == 2
  3508. assert axs[1].get_adjustable() == adjustable
  3509. fig, axs = plt.subplots(nrows=2, sharex=True)
  3510. axs[0].set_aspect(2, adjustable=adjustable)
  3511. assert axs[1].get_aspect() == 'auto'
  3512. def test_shared_with_aspect_2():
  3513. # Share 2 axes only with 'box':
  3514. fig, axs = plt.subplots(nrows=2, sharex=True, sharey=True)
  3515. axs[0].set_aspect(2, share=True)
  3516. axs[0].plot([1, 2], [3, 4])
  3517. axs[1].plot([3, 4], [1, 2])
  3518. plt.draw() # Trigger apply_aspect().
  3519. assert axs[0].get_xlim() == axs[1].get_xlim()
  3520. assert axs[0].get_ylim() == axs[1].get_ylim()
  3521. def test_shared_with_aspect_3():
  3522. # Different aspect ratios:
  3523. for adjustable in ['box', 'datalim']:
  3524. fig, axs = plt.subplots(nrows=2, sharey=True)
  3525. axs[0].set_aspect(2, adjustable=adjustable)
  3526. axs[1].set_aspect(0.5, adjustable=adjustable)
  3527. axs[0].plot([1, 2], [3, 4])
  3528. axs[1].plot([3, 4], [1, 2])
  3529. plt.draw() # Trigger apply_aspect().
  3530. assert axs[0].get_xlim() != axs[1].get_xlim()
  3531. assert axs[0].get_ylim() == axs[1].get_ylim()
  3532. fig_aspect = fig.bbox_inches.height / fig.bbox_inches.width
  3533. for ax in axs:
  3534. p = ax.get_position()
  3535. box_aspect = p.height / p.width
  3536. lim_aspect = ax.viewLim.height / ax.viewLim.width
  3537. expected = fig_aspect * box_aspect / lim_aspect
  3538. assert round(expected, 4) == round(ax.get_aspect(), 4)
  3539. @pytest.mark.parametrize('twin', ('x', 'y'))
  3540. def test_twin_with_aspect(twin):
  3541. fig, ax = plt.subplots()
  3542. # test twinx or twiny
  3543. ax_twin = getattr(ax, 'twin{}'.format(twin))()
  3544. ax.set_aspect(5)
  3545. ax_twin.set_aspect(2)
  3546. assert_array_equal(ax.bbox.extents,
  3547. ax_twin.bbox.extents)
  3548. def test_relim_visible_only():
  3549. x1 = (0., 10.)
  3550. y1 = (0., 10.)
  3551. x2 = (-10., 20.)
  3552. y2 = (-10., 30.)
  3553. fig = matplotlib.figure.Figure()
  3554. ax = fig.add_subplot(111)
  3555. ax.plot(x1, y1)
  3556. assert ax.get_xlim() == x1
  3557. assert ax.get_ylim() == y1
  3558. l = ax.plot(x2, y2)
  3559. assert ax.get_xlim() == x2
  3560. assert ax.get_ylim() == y2
  3561. l[0].set_visible(False)
  3562. assert ax.get_xlim() == x2
  3563. assert ax.get_ylim() == y2
  3564. ax.relim(visible_only=True)
  3565. ax.autoscale_view()
  3566. assert ax.get_xlim() == x1
  3567. assert ax.get_ylim() == y1
  3568. def test_text_labelsize():
  3569. """
  3570. tests for issue #1172
  3571. """
  3572. fig = plt.figure()
  3573. ax = fig.gca()
  3574. ax.tick_params(labelsize='large')
  3575. ax.tick_params(direction='out')
  3576. @image_comparison(['pie_default.png'])
  3577. def test_pie_default():
  3578. # The slices will be ordered and plotted counter-clockwise.
  3579. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  3580. sizes = [15, 30, 45, 10]
  3581. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3582. explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
  3583. fig1, ax1 = plt.subplots(figsize=(8, 6))
  3584. ax1.pie(sizes, explode=explode, labels=labels, colors=colors,
  3585. autopct='%1.1f%%', shadow=True, startangle=90)
  3586. @image_comparison(['pie_linewidth_0', 'pie_linewidth_0', 'pie_linewidth_0'],
  3587. extensions=['png'])
  3588. def test_pie_linewidth_0():
  3589. # The slices will be ordered and plotted counter-clockwise.
  3590. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  3591. sizes = [15, 30, 45, 10]
  3592. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3593. explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
  3594. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  3595. autopct='%1.1f%%', shadow=True, startangle=90,
  3596. wedgeprops={'linewidth': 0})
  3597. # Set aspect ratio to be equal so that pie is drawn as a circle.
  3598. plt.axis('equal')
  3599. # Reuse testcase from above for a labeled data test
  3600. data = {"l": labels, "s": sizes, "c": colors, "ex": explode}
  3601. fig = plt.figure()
  3602. ax = fig.gca()
  3603. ax.pie("s", explode="ex", labels="l", colors="c",
  3604. autopct='%1.1f%%', shadow=True, startangle=90,
  3605. wedgeprops={'linewidth': 0}, data=data)
  3606. ax.axis('equal')
  3607. # And again to test the pyplot functions which should also be able to be
  3608. # called with a data kwarg
  3609. plt.figure()
  3610. plt.pie("s", explode="ex", labels="l", colors="c",
  3611. autopct='%1.1f%%', shadow=True, startangle=90,
  3612. wedgeprops={'linewidth': 0}, data=data)
  3613. plt.axis('equal')
  3614. @image_comparison(['pie_center_radius.png'])
  3615. def test_pie_center_radius():
  3616. # The slices will be ordered and plotted counter-clockwise.
  3617. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  3618. sizes = [15, 30, 45, 10]
  3619. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3620. explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
  3621. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  3622. autopct='%1.1f%%', shadow=True, startangle=90,
  3623. wedgeprops={'linewidth': 0}, center=(1, 2), radius=1.5)
  3624. plt.annotate("Center point", xy=(1, 2), xytext=(1, 1.5),
  3625. arrowprops=dict(arrowstyle="->",
  3626. connectionstyle="arc3"))
  3627. # Set aspect ratio to be equal so that pie is drawn as a circle.
  3628. plt.axis('equal')
  3629. @image_comparison(['pie_linewidth_2.png'])
  3630. def test_pie_linewidth_2():
  3631. # The slices will be ordered and plotted counter-clockwise.
  3632. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  3633. sizes = [15, 30, 45, 10]
  3634. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3635. explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
  3636. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  3637. autopct='%1.1f%%', shadow=True, startangle=90,
  3638. wedgeprops={'linewidth': 2})
  3639. # Set aspect ratio to be equal so that pie is drawn as a circle.
  3640. plt.axis('equal')
  3641. @image_comparison(['pie_ccw_true.png'])
  3642. def test_pie_ccw_true():
  3643. # The slices will be ordered and plotted counter-clockwise.
  3644. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  3645. sizes = [15, 30, 45, 10]
  3646. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3647. explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
  3648. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  3649. autopct='%1.1f%%', shadow=True, startangle=90,
  3650. counterclock=True)
  3651. # Set aspect ratio to be equal so that pie is drawn as a circle.
  3652. plt.axis('equal')
  3653. @image_comparison(['pie_frame_grid.png'])
  3654. def test_pie_frame_grid():
  3655. # The slices will be ordered and plotted counter-clockwise.
  3656. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  3657. sizes = [15, 30, 45, 10]
  3658. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3659. # only "explode" the 2nd slice (i.e. 'Hogs')
  3660. explode = (0, 0.1, 0, 0)
  3661. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  3662. autopct='%1.1f%%', shadow=True, startangle=90,
  3663. wedgeprops={'linewidth': 0},
  3664. frame=True, center=(2, 2))
  3665. plt.pie(sizes[::-1], explode=explode, labels=labels, colors=colors,
  3666. autopct='%1.1f%%', shadow=True, startangle=90,
  3667. wedgeprops={'linewidth': 0},
  3668. frame=True, center=(5, 2))
  3669. plt.pie(sizes, explode=explode[::-1], labels=labels, colors=colors,
  3670. autopct='%1.1f%%', shadow=True, startangle=90,
  3671. wedgeprops={'linewidth': 0},
  3672. frame=True, center=(3, 5))
  3673. # Set aspect ratio to be equal so that pie is drawn as a circle.
  3674. plt.axis('equal')
  3675. @image_comparison(['pie_rotatelabels_true.png'])
  3676. def test_pie_rotatelabels_true():
  3677. # The slices will be ordered and plotted counter-clockwise.
  3678. labels = 'Hogwarts', 'Frogs', 'Dogs', 'Logs'
  3679. sizes = [15, 30, 45, 10]
  3680. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3681. explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
  3682. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  3683. autopct='%1.1f%%', shadow=True, startangle=90,
  3684. rotatelabels=True)
  3685. # Set aspect ratio to be equal so that pie is drawn as a circle.
  3686. plt.axis('equal')
  3687. @image_comparison(['pie_no_label.png'])
  3688. def test_pie_nolabel_but_legend():
  3689. labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
  3690. sizes = [15, 30, 45, 10]
  3691. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  3692. explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')
  3693. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  3694. autopct='%1.1f%%', shadow=True, startangle=90, labeldistance=None,
  3695. rotatelabels=True)
  3696. plt.axis('equal')
  3697. plt.ylim(-1.2, 1.2)
  3698. plt.legend()
  3699. def test_pie_textprops():
  3700. data = [23, 34, 45]
  3701. labels = ["Long name 1", "Long name 2", "Long name 3"]
  3702. textprops = dict(horizontalalignment="center",
  3703. verticalalignment="top",
  3704. rotation=90,
  3705. rotation_mode="anchor",
  3706. size=12, color="red")
  3707. _, texts, autopct = plt.gca().pie(data, labels=labels, autopct='%.2f',
  3708. textprops=textprops)
  3709. for labels in [texts, autopct]:
  3710. for tx in labels:
  3711. assert tx.get_ha() == textprops["horizontalalignment"]
  3712. assert tx.get_va() == textprops["verticalalignment"]
  3713. assert tx.get_rotation() == textprops["rotation"]
  3714. assert tx.get_rotation_mode() == textprops["rotation_mode"]
  3715. assert tx.get_size() == textprops["size"]
  3716. assert tx.get_color() == textprops["color"]
  3717. def test_pie_get_negative_values():
  3718. # Test the ValueError raised when feeding negative values into axes.pie
  3719. fig, ax = plt.subplots()
  3720. with pytest.raises(ValueError):
  3721. ax.pie([5, 5, -3], explode=[0, .1, .2])
  3722. def test_normalize_kwarg_warn_pie():
  3723. fig, ax = plt.subplots()
  3724. with pytest.warns(MatplotlibDeprecationWarning):
  3725. ax.pie(x=[0], normalize=None)
  3726. def test_normalize_kwarg_pie():
  3727. fig, ax = plt.subplots()
  3728. x = [0.3, 0.3, 0.1]
  3729. t1 = ax.pie(x=x, normalize=True)
  3730. assert abs(t1[0][-1].theta2 - 360.) < 1e-3
  3731. t2 = ax.pie(x=x, normalize=False)
  3732. assert abs(t2[0][-1].theta2 - 360.) > 1e-3
  3733. @image_comparison(['set_get_ticklabels.png'])
  3734. def test_set_get_ticklabels():
  3735. # test issue 2246
  3736. fig, ax = plt.subplots(2)
  3737. ha = ['normal', 'set_x/yticklabels']
  3738. ax[0].plot(np.arange(10))
  3739. ax[0].set_title(ha[0])
  3740. ax[1].plot(np.arange(10))
  3741. ax[1].set_title(ha[1])
  3742. # set ticklabel to 1 plot in normal way
  3743. ax[0].set_xticks(range(10))
  3744. ax[0].set_yticks(range(10))
  3745. ax[0].set_xticklabels(['a', 'b', 'c', 'd'] + 6 * [''])
  3746. ax[0].set_yticklabels(['11', '12', '13', '14'] + 6 * [''])
  3747. # set ticklabel to the other plot, expect the 2 plots have same label
  3748. # setting pass get_ticklabels return value as ticklabels argument
  3749. ax[1].set_xticks(ax[0].get_xticks())
  3750. ax[1].set_yticks(ax[0].get_yticks())
  3751. ax[1].set_xticklabels(ax[0].get_xticklabels())
  3752. ax[1].set_yticklabels(ax[0].get_yticklabels())
  3753. def test_subsampled_ticklabels():
  3754. # test issue 11937
  3755. fig, ax = plt.subplots()
  3756. ax.plot(np.arange(10))
  3757. ax.xaxis.set_ticks(np.arange(10) + 0.1)
  3758. ax.locator_params(nbins=5)
  3759. ax.xaxis.set_ticklabels([c for c in "bcdefghijk"])
  3760. plt.draw()
  3761. labels = [t.get_text() for t in ax.xaxis.get_ticklabels()]
  3762. assert labels == ['b', 'd', 'f', 'h', 'j']
  3763. def test_mismatched_ticklabels():
  3764. fig, ax = plt.subplots()
  3765. ax.plot(np.arange(10))
  3766. ax.xaxis.set_ticks([1.5, 2.5])
  3767. with pytest.raises(ValueError):
  3768. ax.xaxis.set_ticklabels(['a', 'b', 'c'])
  3769. def test_empty_ticks_fixed_loc():
  3770. # Smoke test that [] can be used to unset all tick labels
  3771. fig, ax = plt.subplots()
  3772. ax.bar([1, 2], [1, 2])
  3773. ax.set_xticks([1, 2])
  3774. ax.set_xticklabels([])
  3775. @image_comparison(['retain_tick_visibility.png'])
  3776. def test_retain_tick_visibility():
  3777. fig, ax = plt.subplots()
  3778. plt.plot([0, 1, 2], [0, -1, 4])
  3779. plt.setp(ax.get_yticklabels(), visible=False)
  3780. ax.tick_params(axis="y", which="both", length=0)
  3781. def test_tick_label_update():
  3782. # test issue 9397
  3783. fig, ax = plt.subplots()
  3784. # Set up a dummy formatter
  3785. def formatter_func(x, pos):
  3786. return "unit value" if x == 1 else ""
  3787. ax.xaxis.set_major_formatter(plt.FuncFormatter(formatter_func))
  3788. # Force some of the x-axis ticks to be outside of the drawn range
  3789. ax.set_xticks([-1, 0, 1, 2, 3])
  3790. ax.set_xlim(-0.5, 2.5)
  3791. ax.figure.canvas.draw()
  3792. tick_texts = [tick.get_text() for tick in ax.xaxis.get_ticklabels()]
  3793. assert tick_texts == ["", "", "unit value", "", ""]
  3794. @image_comparison(['o_marker_path_snap.png'], savefig_kwarg={'dpi': 72})
  3795. def test_o_marker_path_snap():
  3796. fig, ax = plt.subplots()
  3797. ax.margins(.1)
  3798. for ms in range(1, 15):
  3799. ax.plot([1, 2, ], np.ones(2) + ms, 'o', ms=ms)
  3800. for ms in np.linspace(1, 10, 25):
  3801. ax.plot([3, 4, ], np.ones(2) + ms, 'o', ms=ms)
  3802. def test_margins():
  3803. # test all ways margins can be called
  3804. data = [1, 10]
  3805. xmin = 0.0
  3806. xmax = len(data) - 1.0
  3807. ymin = min(data)
  3808. ymax = max(data)
  3809. fig1, ax1 = plt.subplots(1, 1)
  3810. ax1.plot(data)
  3811. ax1.margins(1)
  3812. assert ax1.margins() == (1, 1)
  3813. assert ax1.get_xlim() == (xmin - (xmax - xmin) * 1,
  3814. xmax + (xmax - xmin) * 1)
  3815. assert ax1.get_ylim() == (ymin - (ymax - ymin) * 1,
  3816. ymax + (ymax - ymin) * 1)
  3817. fig2, ax2 = plt.subplots(1, 1)
  3818. ax2.plot(data)
  3819. ax2.margins(0.5, 2)
  3820. assert ax2.margins() == (0.5, 2)
  3821. assert ax2.get_xlim() == (xmin - (xmax - xmin) * 0.5,
  3822. xmax + (xmax - xmin) * 0.5)
  3823. assert ax2.get_ylim() == (ymin - (ymax - ymin) * 2,
  3824. ymax + (ymax - ymin) * 2)
  3825. fig3, ax3 = plt.subplots(1, 1)
  3826. ax3.plot(data)
  3827. ax3.margins(x=-0.2, y=0.5)
  3828. assert ax3.margins() == (-0.2, 0.5)
  3829. assert ax3.get_xlim() == (xmin - (xmax - xmin) * -0.2,
  3830. xmax + (xmax - xmin) * -0.2)
  3831. assert ax3.get_ylim() == (ymin - (ymax - ymin) * 0.5,
  3832. ymax + (ymax - ymin) * 0.5)
  3833. def test_set_margin_updates_limits():
  3834. mpl.style.use("default")
  3835. fig, ax = plt.subplots()
  3836. ax.plot([1, 2], [1, 2])
  3837. ax.set(xscale="log", xmargin=0)
  3838. assert ax.get_xlim() == (1, 2)
  3839. def test_length_one_hist():
  3840. fig, ax = plt.subplots()
  3841. ax.hist(1)
  3842. ax.hist([1])
  3843. def test_pathological_hexbin():
  3844. # issue #2863
  3845. mylist = [10] * 100
  3846. fig, ax = plt.subplots(1, 1)
  3847. ax.hexbin(mylist, mylist)
  3848. fig.savefig(io.BytesIO()) # Check that no warning is emitted.
  3849. def test_color_None():
  3850. # issue 3855
  3851. fig, ax = plt.subplots()
  3852. ax.plot([1, 2], [1, 2], color=None)
  3853. def test_color_alias():
  3854. # issues 4157 and 4162
  3855. fig, ax = plt.subplots()
  3856. line = ax.plot([0, 1], c='lime')[0]
  3857. assert 'lime' == line.get_color()
  3858. def test_numerical_hist_label():
  3859. fig, ax = plt.subplots()
  3860. ax.hist([range(15)] * 5, label=range(5))
  3861. ax.legend()
  3862. def test_unicode_hist_label():
  3863. fig, ax = plt.subplots()
  3864. a = (b'\xe5\xbe\x88\xe6\xbc\x82\xe4\xba\xae, ' +
  3865. b'r\xc3\xb6m\xc3\xa4n ch\xc3\xa4r\xc3\xa1ct\xc3\xa8rs')
  3866. b = b'\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d'
  3867. labels = [a.decode('utf-8'),
  3868. 'hi aardvark',
  3869. b.decode('utf-8'),
  3870. ]
  3871. ax.hist([range(15)] * 3, label=labels)
  3872. ax.legend()
  3873. def test_move_offsetlabel():
  3874. data = np.random.random(10) * 1e-22
  3875. fig, ax = plt.subplots()
  3876. ax.plot(data)
  3877. fig.canvas.draw()
  3878. before = ax.yaxis.offsetText.get_position()
  3879. assert ax.yaxis.offsetText.get_horizontalalignment() == 'left'
  3880. ax.yaxis.tick_right()
  3881. fig.canvas.draw()
  3882. after = ax.yaxis.offsetText.get_position()
  3883. assert after[0] > before[0] and after[1] == before[1]
  3884. assert ax.yaxis.offsetText.get_horizontalalignment() == 'right'
  3885. fig, ax = plt.subplots()
  3886. ax.plot(data)
  3887. fig.canvas.draw()
  3888. before = ax.xaxis.offsetText.get_position()
  3889. assert ax.xaxis.offsetText.get_verticalalignment() == 'top'
  3890. ax.xaxis.tick_top()
  3891. fig.canvas.draw()
  3892. after = ax.xaxis.offsetText.get_position()
  3893. assert after[0] == before[0] and after[1] > before[1]
  3894. assert ax.xaxis.offsetText.get_verticalalignment() == 'bottom'
  3895. @image_comparison(['rc_spines.png'], savefig_kwarg={'dpi': 40})
  3896. def test_rc_spines():
  3897. rc_dict = {
  3898. 'axes.spines.left': False,
  3899. 'axes.spines.right': False,
  3900. 'axes.spines.top': False,
  3901. 'axes.spines.bottom': False}
  3902. with matplotlib.rc_context(rc_dict):
  3903. fig, ax = plt.subplots()
  3904. @image_comparison(['rc_grid.png'], savefig_kwarg={'dpi': 40})
  3905. def test_rc_grid():
  3906. fig = plt.figure()
  3907. rc_dict0 = {
  3908. 'axes.grid': True,
  3909. 'axes.grid.axis': 'both'
  3910. }
  3911. rc_dict1 = {
  3912. 'axes.grid': True,
  3913. 'axes.grid.axis': 'x'
  3914. }
  3915. rc_dict2 = {
  3916. 'axes.grid': True,
  3917. 'axes.grid.axis': 'y'
  3918. }
  3919. dict_list = [rc_dict0, rc_dict1, rc_dict2]
  3920. for i, rc_dict in enumerate(dict_list, 1):
  3921. with matplotlib.rc_context(rc_dict):
  3922. fig.add_subplot(3, 1, i)
  3923. def test_rc_tick():
  3924. d = {'xtick.bottom': False, 'xtick.top': True,
  3925. 'ytick.left': True, 'ytick.right': False}
  3926. with plt.rc_context(rc=d):
  3927. fig = plt.figure()
  3928. ax1 = fig.add_subplot(1, 1, 1)
  3929. xax = ax1.xaxis
  3930. yax = ax1.yaxis
  3931. # tick1On bottom/left
  3932. assert not xax._major_tick_kw['tick1On']
  3933. assert xax._major_tick_kw['tick2On']
  3934. assert not xax._minor_tick_kw['tick1On']
  3935. assert xax._minor_tick_kw['tick2On']
  3936. assert yax._major_tick_kw['tick1On']
  3937. assert not yax._major_tick_kw['tick2On']
  3938. assert yax._minor_tick_kw['tick1On']
  3939. assert not yax._minor_tick_kw['tick2On']
  3940. def test_rc_major_minor_tick():
  3941. d = {'xtick.top': True, 'ytick.right': True, # Enable all ticks
  3942. 'xtick.bottom': True, 'ytick.left': True,
  3943. # Selectively disable
  3944. 'xtick.minor.bottom': False, 'xtick.major.bottom': False,
  3945. 'ytick.major.left': False, 'ytick.minor.left': False}
  3946. with plt.rc_context(rc=d):
  3947. fig = plt.figure()
  3948. ax1 = fig.add_subplot(1, 1, 1)
  3949. xax = ax1.xaxis
  3950. yax = ax1.yaxis
  3951. # tick1On bottom/left
  3952. assert not xax._major_tick_kw['tick1On']
  3953. assert xax._major_tick_kw['tick2On']
  3954. assert not xax._minor_tick_kw['tick1On']
  3955. assert xax._minor_tick_kw['tick2On']
  3956. assert not yax._major_tick_kw['tick1On']
  3957. assert yax._major_tick_kw['tick2On']
  3958. assert not yax._minor_tick_kw['tick1On']
  3959. assert yax._minor_tick_kw['tick2On']
  3960. def test_square_plot():
  3961. x = np.arange(4)
  3962. y = np.array([1., 3., 5., 7.])
  3963. fig, ax = plt.subplots()
  3964. ax.plot(x, y, 'mo')
  3965. ax.axis('square')
  3966. xlim, ylim = ax.get_xlim(), ax.get_ylim()
  3967. assert np.diff(xlim) == np.diff(ylim)
  3968. assert ax.get_aspect() == 1
  3969. assert_array_almost_equal(
  3970. ax.get_position(original=True).extents, (0.125, 0.1, 0.9, 0.9))
  3971. assert_array_almost_equal(
  3972. ax.get_position(original=False).extents, (0.2125, 0.1, 0.8125, 0.9))
  3973. def test_bad_plot_args():
  3974. with pytest.raises(ValueError):
  3975. plt.plot(None)
  3976. with pytest.raises(ValueError):
  3977. plt.plot(None, None)
  3978. with pytest.raises(ValueError):
  3979. plt.plot(np.zeros((2, 2)), np.zeros((2, 3)))
  3980. with pytest.raises(ValueError):
  3981. plt.plot((np.arange(5).reshape((1, -1)), np.arange(5).reshape(-1, 1)))
  3982. @pytest.mark.parametrize(
  3983. "xy, cls", [
  3984. ((), mpl.image.AxesImage), # (0, N)
  3985. (((3, 7), (2, 6)), mpl.image.AxesImage), # (xmin, xmax)
  3986. ((range(5), range(4)), mpl.image.AxesImage), # regular grid
  3987. (([1, 2, 4, 8, 16], [0, 1, 2, 3]), # irregular grid
  3988. mpl.image.PcolorImage),
  3989. ((np.random.random((4, 5)), np.random.random((4, 5))), # 2D coords
  3990. mpl.collections.QuadMesh),
  3991. ]
  3992. )
  3993. @pytest.mark.parametrize(
  3994. "data", [np.arange(12).reshape((3, 4)), np.random.rand(3, 4, 3)]
  3995. )
  3996. def test_pcolorfast(xy, data, cls):
  3997. fig, ax = plt.subplots()
  3998. assert type(ax.pcolorfast(*xy, data)) == cls
  3999. def test_shared_scale():
  4000. fig, axs = plt.subplots(2, 2, sharex=True, sharey=True)
  4001. axs[0, 0].set_xscale("log")
  4002. axs[0, 0].set_yscale("log")
  4003. for ax in axs.flat:
  4004. assert ax.get_yscale() == 'log'
  4005. assert ax.get_xscale() == 'log'
  4006. axs[1, 1].set_xscale("linear")
  4007. axs[1, 1].set_yscale("linear")
  4008. for ax in axs.flat:
  4009. assert ax.get_yscale() == 'linear'
  4010. assert ax.get_xscale() == 'linear'
  4011. def test_shared_bool():
  4012. with pytest.raises(TypeError):
  4013. plt.subplot(sharex=True)
  4014. with pytest.raises(TypeError):
  4015. plt.subplot(sharey=True)
  4016. def test_violin_point_mass():
  4017. """Violin plot should handle point mass pdf gracefully."""
  4018. plt.violinplot(np.array([0, 0]))
  4019. def generate_errorbar_inputs():
  4020. base_xy = cycler('x', [np.arange(5)]) + cycler('y', [np.ones(5)])
  4021. err_cycler = cycler('err', [1,
  4022. [1, 1, 1, 1, 1],
  4023. [[1, 1, 1, 1, 1],
  4024. [1, 1, 1, 1, 1]],
  4025. np.ones(5),
  4026. np.ones((2, 5)),
  4027. None
  4028. ])
  4029. xerr_cy = cycler('xerr', err_cycler)
  4030. yerr_cy = cycler('yerr', err_cycler)
  4031. empty = ((cycler('x', [[]]) + cycler('y', [[]])) *
  4032. cycler('xerr', [[], None]) * cycler('yerr', [[], None]))
  4033. xerr_only = base_xy * xerr_cy
  4034. yerr_only = base_xy * yerr_cy
  4035. both_err = base_xy * yerr_cy * xerr_cy
  4036. return [*xerr_only, *yerr_only, *both_err, *empty]
  4037. @pytest.mark.parametrize('kwargs', generate_errorbar_inputs())
  4038. def test_errorbar_inputs_shotgun(kwargs):
  4039. ax = plt.gca()
  4040. eb = ax.errorbar(**kwargs)
  4041. eb.remove()
  4042. @image_comparison(["dash_offset"], remove_text=True)
  4043. def test_dash_offset():
  4044. fig, ax = plt.subplots()
  4045. x = np.linspace(0, 10)
  4046. y = np.ones_like(x)
  4047. for j in range(0, 100, 2):
  4048. ax.plot(x, j*y, ls=(j, (10, 10)), lw=5, color='k')
  4049. def test_title_pad():
  4050. # check that title padding puts the title in the right
  4051. # place...
  4052. fig, ax = plt.subplots()
  4053. ax.set_title('aardvark', pad=30.)
  4054. m = ax.titleOffsetTrans.get_matrix()
  4055. assert m[1, -1] == (30. / 72. * fig.dpi)
  4056. ax.set_title('aardvark', pad=0.)
  4057. m = ax.titleOffsetTrans.get_matrix()
  4058. assert m[1, -1] == 0.
  4059. # check that it is reverted...
  4060. ax.set_title('aardvark', pad=None)
  4061. m = ax.titleOffsetTrans.get_matrix()
  4062. assert m[1, -1] == (matplotlib.rcParams['axes.titlepad'] / 72. * fig.dpi)
  4063. def test_title_location_roundtrip():
  4064. fig, ax = plt.subplots()
  4065. # set default title location
  4066. plt.rcParams['axes.titlelocation'] = 'center'
  4067. ax.set_title('aardvark')
  4068. ax.set_title('left', loc='left')
  4069. ax.set_title('right', loc='right')
  4070. assert 'left' == ax.get_title(loc='left')
  4071. assert 'right' == ax.get_title(loc='right')
  4072. assert 'aardvark' == ax.get_title(loc='center')
  4073. with pytest.raises(ValueError):
  4074. ax.get_title(loc='foo')
  4075. with pytest.raises(ValueError):
  4076. ax.set_title('fail', loc='foo')
  4077. @image_comparison(["loglog.png"], remove_text=True, tol=0.02)
  4078. def test_loglog():
  4079. fig, ax = plt.subplots()
  4080. x = np.arange(1, 11)
  4081. ax.loglog(x, x**3, lw=5)
  4082. ax.tick_params(length=25, width=2)
  4083. ax.tick_params(length=15, width=2, which='minor')
  4084. @pytest.mark.parametrize("new_api", [False, True])
  4085. @image_comparison(["test_loglog_nonpos.png"], remove_text=True, style='mpl20')
  4086. def test_loglog_nonpos(new_api):
  4087. fig, axs = plt.subplots(3, 3)
  4088. x = np.arange(1, 11)
  4089. y = x**3
  4090. y[7] = -3.
  4091. x[4] = -10
  4092. for (i, j), ax in np.ndenumerate(axs):
  4093. mcx = ['mask', 'clip', ''][j]
  4094. mcy = ['mask', 'clip', ''][i]
  4095. if new_api:
  4096. if mcx == mcy:
  4097. if mcx:
  4098. ax.loglog(x, y**3, lw=2, nonpositive=mcx)
  4099. else:
  4100. ax.loglog(x, y**3, lw=2)
  4101. else:
  4102. ax.loglog(x, y**3, lw=2)
  4103. if mcx:
  4104. ax.set_xscale("log", nonpositive=mcx)
  4105. if mcy:
  4106. ax.set_yscale("log", nonpositive=mcy)
  4107. else:
  4108. kws = {}
  4109. if mcx:
  4110. kws['nonposx'] = mcx
  4111. if mcy:
  4112. kws['nonposy'] = mcy
  4113. with (pytest.warns(MatplotlibDeprecationWarning) if kws
  4114. else nullcontext()):
  4115. ax.loglog(x, y**3, lw=2, **kws)
  4116. @pytest.mark.style('default')
  4117. def test_axes_margins():
  4118. fig, ax = plt.subplots()
  4119. ax.plot([0, 1, 2, 3])
  4120. assert ax.get_ybound()[0] != 0
  4121. fig, ax = plt.subplots()
  4122. ax.bar([0, 1, 2, 3], [1, 1, 1, 1])
  4123. assert ax.get_ybound()[0] == 0
  4124. fig, ax = plt.subplots()
  4125. ax.barh([0, 1, 2, 3], [1, 1, 1, 1])
  4126. assert ax.get_xbound()[0] == 0
  4127. fig, ax = plt.subplots()
  4128. ax.pcolor(np.zeros((10, 10)))
  4129. assert ax.get_xbound() == (0, 10)
  4130. assert ax.get_ybound() == (0, 10)
  4131. fig, ax = plt.subplots()
  4132. ax.pcolorfast(np.zeros((10, 10)))
  4133. assert ax.get_xbound() == (0, 10)
  4134. assert ax.get_ybound() == (0, 10)
  4135. fig, ax = plt.subplots()
  4136. ax.hist(np.arange(10))
  4137. assert ax.get_ybound()[0] == 0
  4138. fig, ax = plt.subplots()
  4139. ax.imshow(np.zeros((10, 10)))
  4140. assert ax.get_xbound() == (-0.5, 9.5)
  4141. assert ax.get_ybound() == (-0.5, 9.5)
  4142. @pytest.fixture(params=['x', 'y'])
  4143. def shared_axis_remover(request):
  4144. def _helper_x(ax):
  4145. ax2 = ax.twinx()
  4146. ax2.remove()
  4147. ax.set_xlim(0, 15)
  4148. r = ax.xaxis.get_major_locator()()
  4149. assert r[-1] > 14
  4150. def _helper_y(ax):
  4151. ax2 = ax.twiny()
  4152. ax2.remove()
  4153. ax.set_ylim(0, 15)
  4154. r = ax.yaxis.get_major_locator()()
  4155. assert r[-1] > 14
  4156. return {"x": _helper_x, "y": _helper_y}[request.param]
  4157. @pytest.fixture(params=['gca', 'subplots', 'subplots_shared', 'add_axes'])
  4158. def shared_axes_generator(request):
  4159. # test all of the ways to get fig/ax sets
  4160. if request.param == 'gca':
  4161. fig = plt.figure()
  4162. ax = fig.gca()
  4163. elif request.param == 'subplots':
  4164. fig, ax = plt.subplots()
  4165. elif request.param == 'subplots_shared':
  4166. fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all')
  4167. ax = ax_lst[0][0]
  4168. elif request.param == 'add_axes':
  4169. fig = plt.figure()
  4170. ax = fig.add_axes([.1, .1, .8, .8])
  4171. return fig, ax
  4172. def test_remove_shared_axes(shared_axes_generator, shared_axis_remover):
  4173. # test all of the ways to get fig/ax sets
  4174. fig, ax = shared_axes_generator
  4175. shared_axis_remover(ax)
  4176. def test_remove_shared_axes_relim():
  4177. fig, ax_lst = plt.subplots(2, 2, sharex='all', sharey='all')
  4178. ax = ax_lst[0][0]
  4179. orig_xlim = ax_lst[0][1].get_xlim()
  4180. ax.remove()
  4181. ax.set_xlim(0, 5)
  4182. assert_array_equal(ax_lst[0][1].get_xlim(), orig_xlim)
  4183. def test_shared_axes_autoscale():
  4184. l = np.arange(-80, 90, 40)
  4185. t = np.random.random_sample((l.size, l.size))
  4186. ax1 = plt.subplot(211)
  4187. ax1.set_xlim(-1000, 1000)
  4188. ax1.set_ylim(-1000, 1000)
  4189. ax1.contour(l, l, t)
  4190. ax2 = plt.subplot(212, sharex=ax1, sharey=ax1)
  4191. ax2.contour(l, l, t)
  4192. assert not ax1.get_autoscalex_on() and not ax2.get_autoscalex_on()
  4193. assert not ax1.get_autoscaley_on() and not ax2.get_autoscaley_on()
  4194. assert ax1.get_xlim() == ax2.get_xlim() == (-1000, 1000)
  4195. assert ax1.get_ylim() == ax2.get_ylim() == (-1000, 1000)
  4196. def test_adjust_numtick_aspect():
  4197. fig, ax = plt.subplots()
  4198. ax.yaxis.get_major_locator().set_params(nbins='auto')
  4199. ax.set_xlim(0, 1000)
  4200. ax.set_aspect('equal')
  4201. fig.canvas.draw()
  4202. assert len(ax.yaxis.get_major_locator()()) == 2
  4203. ax.set_ylim(0, 1000)
  4204. fig.canvas.draw()
  4205. assert len(ax.yaxis.get_major_locator()()) > 2
  4206. @image_comparison(["auto_numticks.png"], style='default')
  4207. def test_auto_numticks():
  4208. # Make tiny, empty subplots, verify that there are only 3 ticks.
  4209. fig, axs = plt.subplots(4, 4)
  4210. @image_comparison(["auto_numticks_log.png"], style='default')
  4211. def test_auto_numticks_log():
  4212. # Verify that there are not too many ticks with a large log range.
  4213. fig, ax = plt.subplots()
  4214. matplotlib.rcParams['axes.autolimit_mode'] = 'round_numbers'
  4215. ax.loglog([1e-20, 1e5], [1e-16, 10])
  4216. def test_broken_barh_empty():
  4217. fig, ax = plt.subplots()
  4218. ax.broken_barh([], (.1, .5))
  4219. def test_broken_barh_timedelta():
  4220. """Check that timedelta works as x, dx pair for this method."""
  4221. fig, ax = plt.subplots()
  4222. d0 = datetime.datetime(2018, 11, 9, 0, 0, 0)
  4223. pp = ax.broken_barh([(d0, datetime.timedelta(hours=1))], [1, 2])
  4224. assert pp.get_paths()[0].vertices[0, 0] == mdates.date2num(d0)
  4225. assert pp.get_paths()[0].vertices[2, 0] == mdates.date2num(d0) + 1 / 24
  4226. def test_pandas_pcolormesh(pd):
  4227. time = pd.date_range('2000-01-01', periods=10)
  4228. depth = np.arange(20)
  4229. data = np.random.rand(19, 9)
  4230. fig, ax = plt.subplots()
  4231. ax.pcolormesh(time, depth, data)
  4232. def test_pandas_indexing_dates(pd):
  4233. dates = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
  4234. values = np.sin(np.array(range(len(dates))))
  4235. df = pd.DataFrame({'dates': dates, 'values': values})
  4236. ax = plt.gca()
  4237. without_zero_index = df[np.array(df.index) % 2 == 1].copy()
  4238. ax.plot('dates', 'values', data=without_zero_index)
  4239. def test_pandas_errorbar_indexing(pd):
  4240. df = pd.DataFrame(np.random.uniform(size=(5, 4)),
  4241. columns=['x', 'y', 'xe', 'ye'],
  4242. index=[1, 2, 3, 4, 5])
  4243. fig, ax = plt.subplots()
  4244. ax.errorbar('x', 'y', xerr='xe', yerr='ye', data=df)
  4245. def test_pandas_index_shape(pd):
  4246. df = pd.DataFrame({"XX": [4, 5, 6], "YY": [7, 1, 2]})
  4247. fig, ax = plt.subplots()
  4248. ax.plot(df.index, df['YY'])
  4249. def test_pandas_indexing_hist(pd):
  4250. ser_1 = pd.Series(data=[1, 2, 2, 3, 3, 4, 4, 4, 4, 5])
  4251. ser_2 = ser_1.iloc[1:]
  4252. fig, ax = plt.subplots()
  4253. ax.hist(ser_2)
  4254. def test_pandas_bar_align_center(pd):
  4255. # Tests fix for issue 8767
  4256. df = pd.DataFrame({'a': range(2), 'b': range(2)})
  4257. fig, ax = plt.subplots(1)
  4258. ax.bar(df.loc[df['a'] == 1, 'b'],
  4259. df.loc[df['a'] == 1, 'b'],
  4260. align='center')
  4261. fig.canvas.draw()
  4262. def test_axis_set_tick_params_labelsize_labelcolor():
  4263. # Tests fix for issue 4346
  4264. axis_1 = plt.subplot()
  4265. axis_1.yaxis.set_tick_params(labelsize=30, labelcolor='red',
  4266. direction='out')
  4267. # Expected values after setting the ticks
  4268. assert axis_1.yaxis.majorTicks[0]._size == 4.0
  4269. assert axis_1.yaxis.majorTicks[0].tick1line.get_color() == 'k'
  4270. assert axis_1.yaxis.majorTicks[0].label1.get_size() == 30.0
  4271. assert axis_1.yaxis.majorTicks[0].label1.get_color() == 'red'
  4272. def test_axes_tick_params_gridlines():
  4273. # Now treating grid params like other Tick params
  4274. ax = plt.subplot()
  4275. ax.tick_params(grid_color='b', grid_linewidth=5, grid_alpha=0.5,
  4276. grid_linestyle='dashdot')
  4277. for axis in ax.xaxis, ax.yaxis:
  4278. assert axis.majorTicks[0].gridline.get_color() == 'b'
  4279. assert axis.majorTicks[0].gridline.get_linewidth() == 5
  4280. assert axis.majorTicks[0].gridline.get_alpha() == 0.5
  4281. assert axis.majorTicks[0].gridline.get_linestyle() == '-.'
  4282. def test_axes_tick_params_ylabelside():
  4283. # Tests fix for issue 10267
  4284. ax = plt.subplot()
  4285. ax.tick_params(labelleft=False, labelright=True,
  4286. which='major')
  4287. ax.tick_params(labelleft=False, labelright=True,
  4288. which='minor')
  4289. # expects left false, right true
  4290. assert ax.yaxis.majorTicks[0].label1.get_visible() is False
  4291. assert ax.yaxis.majorTicks[0].label2.get_visible() is True
  4292. assert ax.yaxis.minorTicks[0].label1.get_visible() is False
  4293. assert ax.yaxis.minorTicks[0].label2.get_visible() is True
  4294. def test_axes_tick_params_xlabelside():
  4295. # Tests fix for issue 10267
  4296. ax = plt.subplot()
  4297. ax.tick_params(labeltop=True, labelbottom=False,
  4298. which='major')
  4299. ax.tick_params(labeltop=True, labelbottom=False,
  4300. which='minor')
  4301. # expects top True, bottom False
  4302. # label1.get_visible() mapped to labelbottom
  4303. # label2.get_visible() mapped to labeltop
  4304. assert ax.xaxis.majorTicks[0].label1.get_visible() is False
  4305. assert ax.xaxis.majorTicks[0].label2.get_visible() is True
  4306. assert ax.xaxis.minorTicks[0].label1.get_visible() is False
  4307. assert ax.xaxis.minorTicks[0].label2.get_visible() is True
  4308. def test_none_kwargs():
  4309. ax = plt.figure().subplots()
  4310. ln, = ax.plot(range(32), linestyle=None)
  4311. assert ln.get_linestyle() == '-'
  4312. def test_ls_ds_conflict():
  4313. # Passing the drawstyle with the linestyle is deprecated since 3.1.
  4314. # We still need to test this until it's removed from the code.
  4315. # But we don't want to see the deprecation warning in the test.
  4316. with matplotlib.cbook._suppress_matplotlib_deprecation_warning(), \
  4317. pytest.raises(ValueError):
  4318. plt.plot(range(32), linestyle='steps-pre:', drawstyle='steps-post')
  4319. def test_bar_uint8():
  4320. xs = [0, 1, 2, 3]
  4321. b = plt.bar(np.array(xs, dtype=np.uint8), [2, 3, 4, 5], align="edge")
  4322. for (patch, x) in zip(b.patches, xs):
  4323. assert patch.xy[0] == x
  4324. @image_comparison(['date_timezone_x.png'], tol=1.0)
  4325. def test_date_timezone_x():
  4326. # Tests issue 5575
  4327. time_index = [datetime.datetime(2016, 2, 22, hour=x,
  4328. tzinfo=dateutil.tz.gettz('Canada/Eastern'))
  4329. for x in range(3)]
  4330. # Same Timezone
  4331. plt.figure(figsize=(20, 12))
  4332. plt.subplot(2, 1, 1)
  4333. plt.plot_date(time_index, [3] * 3, tz='Canada/Eastern')
  4334. # Different Timezone
  4335. plt.subplot(2, 1, 2)
  4336. plt.plot_date(time_index, [3] * 3, tz='UTC')
  4337. @image_comparison(['date_timezone_y.png'])
  4338. def test_date_timezone_y():
  4339. # Tests issue 5575
  4340. time_index = [datetime.datetime(2016, 2, 22, hour=x,
  4341. tzinfo=dateutil.tz.gettz('Canada/Eastern'))
  4342. for x in range(3)]
  4343. # Same Timezone
  4344. plt.figure(figsize=(20, 12))
  4345. plt.subplot(2, 1, 1)
  4346. plt.plot_date([3] * 3,
  4347. time_index, tz='Canada/Eastern', xdate=False, ydate=True)
  4348. # Different Timezone
  4349. plt.subplot(2, 1, 2)
  4350. plt.plot_date([3] * 3, time_index, tz='UTC', xdate=False, ydate=True)
  4351. @image_comparison(['date_timezone_x_and_y.png'], tol=1.0)
  4352. def test_date_timezone_x_and_y():
  4353. # Tests issue 5575
  4354. UTC = datetime.timezone.utc
  4355. time_index = [datetime.datetime(2016, 2, 22, hour=x, tzinfo=UTC)
  4356. for x in range(3)]
  4357. # Same Timezone
  4358. plt.figure(figsize=(20, 12))
  4359. plt.subplot(2, 1, 1)
  4360. plt.plot_date(time_index, time_index, tz='UTC', ydate=True)
  4361. # Different Timezone
  4362. plt.subplot(2, 1, 2)
  4363. plt.plot_date(time_index, time_index, tz='US/Eastern', ydate=True)
  4364. @image_comparison(['axisbelow.png'], remove_text=True)
  4365. def test_axisbelow():
  4366. # Test 'line' setting added in 6287.
  4367. # Show only grids, not frame or ticks, to make this test
  4368. # independent of future change to drawing order of those elements.
  4369. axs = plt.figure().subplots(ncols=3, sharex=True, sharey=True)
  4370. settings = (False, 'line', True)
  4371. for ax, setting in zip(axs, settings):
  4372. ax.plot((0, 10), (0, 10), lw=10, color='m')
  4373. circ = mpatches.Circle((3, 3), color='r')
  4374. ax.add_patch(circ)
  4375. ax.grid(color='c', linestyle='-', linewidth=3)
  4376. ax.tick_params(top=False, bottom=False,
  4377. left=False, right=False)
  4378. for spine in ax.spines.values():
  4379. spine.set_visible(False)
  4380. ax.set_axisbelow(setting)
  4381. def test_titletwiny():
  4382. plt.style.use('mpl20')
  4383. fig, ax = plt.subplots(dpi=72)
  4384. ax2 = ax.twiny()
  4385. xlabel2 = ax2.set_xlabel('Xlabel2')
  4386. title = ax.set_title('Title')
  4387. fig.canvas.draw()
  4388. renderer = fig.canvas.get_renderer()
  4389. # ------- Test that title is put above Xlabel2 (Xlabel2 at top) ----------
  4390. bbox_y0_title = title.get_window_extent(renderer).y0 # bottom of title
  4391. bbox_y1_xlabel2 = xlabel2.get_window_extent(renderer).y1 # top of xlabel2
  4392. y_diff = bbox_y0_title - bbox_y1_xlabel2
  4393. assert np.isclose(y_diff, 3)
  4394. def test_titlesetpos():
  4395. # Test that title stays put if we set it manually
  4396. fig, ax = plt.subplots()
  4397. fig.subplots_adjust(top=0.8)
  4398. ax2 = ax.twiny()
  4399. ax.set_xlabel('Xlabel')
  4400. ax2.set_xlabel('Xlabel2')
  4401. ax.set_title('Title')
  4402. pos = (0.5, 1.11)
  4403. ax.title.set_position(pos)
  4404. renderer = fig.canvas.get_renderer()
  4405. ax._update_title_position(renderer)
  4406. assert ax.title.get_position() == pos
  4407. def test_title_xticks_top():
  4408. # Test that title moves if xticks on top of axes.
  4409. mpl.rcParams['axes.titley'] = None
  4410. fig, ax = plt.subplots()
  4411. ax.xaxis.set_ticks_position('top')
  4412. ax.set_title('xlabel top')
  4413. fig.canvas.draw()
  4414. assert ax.title.get_position()[1] > 1.04
  4415. def test_title_xticks_top_both():
  4416. # Test that title moves if xticks on top of axes.
  4417. mpl.rcParams['axes.titley'] = None
  4418. fig, ax = plt.subplots()
  4419. ax.tick_params(axis="x",
  4420. bottom=True, top=True, labelbottom=True, labeltop=True)
  4421. ax.set_title('xlabel top')
  4422. fig.canvas.draw()
  4423. assert ax.title.get_position()[1] > 1.04
  4424. def test_title_no_move_off_page():
  4425. # If an axes is off the figure (ie. if it is cropped during a save)
  4426. # make sure that the automatic title repositioning does not get done.
  4427. mpl.rcParams['axes.titley'] = None
  4428. fig = plt.figure()
  4429. ax = fig.add_axes([0.1, -0.5, 0.8, 0.2])
  4430. ax.tick_params(axis="x",
  4431. bottom=True, top=True, labelbottom=True, labeltop=True)
  4432. tt = ax.set_title('Boo')
  4433. fig.canvas.draw()
  4434. assert tt.get_position()[1] == 1.0
  4435. def test_offset_label_color():
  4436. # Tests issue 6440
  4437. fig = plt.figure()
  4438. ax = fig.add_subplot(1, 1, 1)
  4439. ax.plot([1.01e9, 1.02e9, 1.03e9])
  4440. ax.yaxis.set_tick_params(labelcolor='red')
  4441. assert ax.yaxis.get_offset_text().get_color() == 'red'
  4442. def test_offset_text_visible():
  4443. fig = plt.figure()
  4444. ax = fig.add_subplot(1, 1, 1)
  4445. ax.plot([1.01e9, 1.02e9, 1.03e9])
  4446. ax.yaxis.set_tick_params(label1On=False, label2On=True)
  4447. assert ax.yaxis.get_offset_text().get_visible()
  4448. ax.yaxis.set_tick_params(label2On=False)
  4449. assert not ax.yaxis.get_offset_text().get_visible()
  4450. def test_large_offset():
  4451. fig, ax = plt.subplots()
  4452. ax.plot((1 + np.array([0, 1.e-12])) * 1.e27)
  4453. fig.canvas.draw()
  4454. def test_barb_units():
  4455. fig, ax = plt.subplots()
  4456. dates = [datetime.datetime(2017, 7, 15, 18, i) for i in range(0, 60, 10)]
  4457. y = np.linspace(0, 5, len(dates))
  4458. u = v = np.linspace(0, 50, len(dates))
  4459. ax.barbs(dates, y, u, v)
  4460. def test_quiver_units():
  4461. fig, ax = plt.subplots()
  4462. dates = [datetime.datetime(2017, 7, 15, 18, i) for i in range(0, 60, 10)]
  4463. y = np.linspace(0, 5, len(dates))
  4464. u = v = np.linspace(0, 50, len(dates))
  4465. ax.quiver(dates, y, u, v)
  4466. def test_bar_color_cycle():
  4467. to_rgb = mcolors.to_rgb
  4468. fig, ax = plt.subplots()
  4469. for j in range(5):
  4470. ln, = ax.plot(range(3))
  4471. brs = ax.bar(range(3), range(3))
  4472. for br in brs:
  4473. assert to_rgb(ln.get_color()) == to_rgb(br.get_facecolor())
  4474. def test_tick_param_label_rotation():
  4475. fix, (ax, ax2) = plt.subplots(1, 2)
  4476. ax.plot([0, 1], [0, 1])
  4477. ax2.plot([0, 1], [0, 1])
  4478. ax.xaxis.set_tick_params(which='both', rotation=75)
  4479. ax.yaxis.set_tick_params(which='both', rotation=90)
  4480. for text in ax.get_xticklabels(which='both'):
  4481. assert text.get_rotation() == 75
  4482. for text in ax.get_yticklabels(which='both'):
  4483. assert text.get_rotation() == 90
  4484. ax2.tick_params(axis='x', labelrotation=53)
  4485. ax2.tick_params(axis='y', rotation=35)
  4486. for text in ax2.get_xticklabels(which='major'):
  4487. assert text.get_rotation() == 53
  4488. for text in ax2.get_yticklabels(which='major'):
  4489. assert text.get_rotation() == 35
  4490. @pytest.mark.style('default')
  4491. def test_fillbetween_cycle():
  4492. fig, ax = plt.subplots()
  4493. for j in range(3):
  4494. cc = ax.fill_between(range(3), range(3))
  4495. target = mcolors.to_rgba('C{}'.format(j))
  4496. assert tuple(cc.get_facecolors().squeeze()) == tuple(target)
  4497. for j in range(3, 6):
  4498. cc = ax.fill_betweenx(range(3), range(3))
  4499. target = mcolors.to_rgba('C{}'.format(j))
  4500. assert tuple(cc.get_facecolors().squeeze()) == tuple(target)
  4501. target = mcolors.to_rgba('k')
  4502. for al in ['facecolor', 'facecolors', 'color']:
  4503. cc = ax.fill_between(range(3), range(3), **{al: 'k'})
  4504. assert tuple(cc.get_facecolors().squeeze()) == tuple(target)
  4505. edge_target = mcolors.to_rgba('k')
  4506. for j, el in enumerate(['edgecolor', 'edgecolors'], start=6):
  4507. cc = ax.fill_between(range(3), range(3), **{el: 'k'})
  4508. face_target = mcolors.to_rgba('C{}'.format(j))
  4509. assert tuple(cc.get_facecolors().squeeze()) == tuple(face_target)
  4510. assert tuple(cc.get_edgecolors().squeeze()) == tuple(edge_target)
  4511. def test_log_margins():
  4512. plt.rcParams['axes.autolimit_mode'] = 'data'
  4513. fig, ax = plt.subplots()
  4514. margin = 0.05
  4515. ax.set_xmargin(margin)
  4516. ax.semilogx([10, 100], [10, 100])
  4517. xlim0, xlim1 = ax.get_xlim()
  4518. transform = ax.xaxis.get_transform()
  4519. xlim0t, xlim1t = transform.transform([xlim0, xlim1])
  4520. x0t, x1t = transform.transform([10, 100])
  4521. delta = (x1t - x0t) * margin
  4522. assert_allclose([xlim0t + delta, xlim1t - delta], [x0t, x1t])
  4523. def test_color_length_mismatch():
  4524. N = 5
  4525. x, y = np.arange(N), np.arange(N)
  4526. colors = np.arange(N+1)
  4527. fig, ax = plt.subplots()
  4528. with pytest.raises(ValueError):
  4529. ax.scatter(x, y, c=colors)
  4530. c_rgb = (0.5, 0.5, 0.5)
  4531. ax.scatter(x, y, c=c_rgb)
  4532. ax.scatter(x, y, c=[c_rgb] * N)
  4533. def test_eventplot_legend():
  4534. plt.eventplot([1.0], label='Label')
  4535. plt.legend()
  4536. def test_bar_broadcast_args():
  4537. fig, ax = plt.subplots()
  4538. # Check that a bar chart with a single height for all bars works.
  4539. ax.bar(range(4), 1)
  4540. # Check that a horizontal chart with one width works.
  4541. ax.barh(0, 1, left=range(4), height=1)
  4542. # Check that edgecolor gets broadcast.
  4543. rect1, rect2 = ax.bar([0, 1], [0, 1], edgecolor=(.1, .2, .3, .4))
  4544. assert rect1.get_edgecolor() == rect2.get_edgecolor() == (.1, .2, .3, .4)
  4545. def test_invalid_axis_limits():
  4546. plt.plot([0, 1], [0, 1])
  4547. with pytest.raises(ValueError):
  4548. plt.xlim(np.nan)
  4549. with pytest.raises(ValueError):
  4550. plt.xlim(np.inf)
  4551. with pytest.raises(ValueError):
  4552. plt.ylim(np.nan)
  4553. with pytest.raises(ValueError):
  4554. plt.ylim(np.inf)
  4555. # Test all 4 combinations of logs/symlogs for minorticks_on()
  4556. @pytest.mark.parametrize('xscale', ['symlog', 'log'])
  4557. @pytest.mark.parametrize('yscale', ['symlog', 'log'])
  4558. def test_minorticks_on(xscale, yscale):
  4559. ax = plt.subplot(111)
  4560. ax.plot([1, 2, 3, 4])
  4561. ax.set_xscale(xscale)
  4562. ax.set_yscale(yscale)
  4563. ax.minorticks_on()
  4564. def test_twinx_knows_limits():
  4565. fig, ax = plt.subplots()
  4566. ax.axvspan(1, 2)
  4567. xtwin = ax.twinx()
  4568. xtwin.plot([0, 0.5], [1, 2])
  4569. # control axis
  4570. fig2, ax2 = plt.subplots()
  4571. ax2.axvspan(1, 2)
  4572. ax2.plot([0, 0.5], [1, 2])
  4573. assert_array_equal(xtwin.viewLim.intervalx, ax2.viewLim.intervalx)
  4574. def test_zero_linewidth():
  4575. # Check that setting a zero linewidth doesn't error
  4576. plt.plot([0, 1], [0, 1], ls='--', lw=0)
  4577. def test_empty_errorbar_legend():
  4578. fig, ax = plt.subplots()
  4579. ax.errorbar([], [], xerr=[], label='empty y')
  4580. ax.errorbar([], [], yerr=[], label='empty x')
  4581. ax.legend()
  4582. @check_figures_equal(extensions=["png"])
  4583. def test_plot_decimal(fig_test, fig_ref):
  4584. x0 = np.arange(-10, 10, 0.3)
  4585. y0 = [5.2 * x ** 3 - 2.1 * x ** 2 + 7.34 * x + 4.5 for x in x0]
  4586. x = [Decimal(i) for i in x0]
  4587. y = [Decimal(i) for i in y0]
  4588. # Test image - line plot with Decimal input
  4589. fig_test.subplots().plot(x, y)
  4590. # Reference image
  4591. fig_ref.subplots().plot(x0, y0)
  4592. # pdf and svg tests fail using travis' old versions of gs and inkscape.
  4593. @check_figures_equal(extensions=["png"])
  4594. def test_markerfacecolor_none_alpha(fig_test, fig_ref):
  4595. fig_test.subplots().plot(0, "o", mfc="none", alpha=.5)
  4596. fig_ref.subplots().plot(0, "o", mfc="w", alpha=.5)
  4597. def test_tick_padding_tightbbox():
  4598. """Test that tick padding gets turned off if axis is off"""
  4599. plt.rcParams["xtick.direction"] = "out"
  4600. plt.rcParams["ytick.direction"] = "out"
  4601. fig, ax = plt.subplots()
  4602. bb = ax.get_tightbbox(fig.canvas.get_renderer())
  4603. ax.axis('off')
  4604. bb2 = ax.get_tightbbox(fig.canvas.get_renderer())
  4605. assert bb.x0 < bb2.x0
  4606. assert bb.y0 < bb2.y0
  4607. def test_inset():
  4608. """
  4609. Ensure that inset_ax argument is indeed optional
  4610. """
  4611. dx, dy = 0.05, 0.05
  4612. # generate 2 2d grids for the x & y bounds
  4613. y, x = np.mgrid[slice(1, 5 + dy, dy),
  4614. slice(1, 5 + dx, dx)]
  4615. z = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
  4616. fig, ax = plt.subplots()
  4617. ax.pcolormesh(x, y, z[:-1, :-1])
  4618. ax.set_aspect(1.)
  4619. ax.apply_aspect()
  4620. # we need to apply_aspect to make the drawing below work.
  4621. xlim = [1.5, 2.15]
  4622. ylim = [2, 2.5]
  4623. rect = [xlim[0], ylim[0], xlim[1] - xlim[0], ylim[1] - ylim[0]]
  4624. rec, connectors = ax.indicate_inset(bounds=rect)
  4625. assert connectors is None
  4626. fig.canvas.draw()
  4627. xx = np.array([[1.5, 2.],
  4628. [2.15, 2.5]])
  4629. assert np.all(rec.get_bbox().get_points() == xx)
  4630. def test_zoom_inset():
  4631. dx, dy = 0.05, 0.05
  4632. # generate 2 2d grids for the x & y bounds
  4633. y, x = np.mgrid[slice(1, 5 + dy, dy),
  4634. slice(1, 5 + dx, dx)]
  4635. z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)
  4636. fig, ax = plt.subplots()
  4637. ax.pcolormesh(x, y, z[:-1, :-1])
  4638. ax.set_aspect(1.)
  4639. ax.apply_aspect()
  4640. # we need to apply_aspect to make the drawing below work.
  4641. # Make the inset_axes... Position axes coordinates...
  4642. axin1 = ax.inset_axes([0.7, 0.7, 0.35, 0.35])
  4643. # redraw the data in the inset axes...
  4644. axin1.pcolormesh(x, y, z[:-1, :-1])
  4645. axin1.set_xlim([1.5, 2.15])
  4646. axin1.set_ylim([2, 2.5])
  4647. axin1.set_aspect(ax.get_aspect())
  4648. rec, connectors = ax.indicate_inset_zoom(axin1)
  4649. assert len(connectors) == 4
  4650. fig.canvas.draw()
  4651. xx = np.array([[1.5, 2.],
  4652. [2.15, 2.5]])
  4653. assert(np.all(rec.get_bbox().get_points() == xx))
  4654. xx = np.array([[0.6325, 0.692308],
  4655. [0.8425, 0.907692]])
  4656. np.testing.assert_allclose(
  4657. axin1.get_position().get_points(), xx, rtol=1e-4)
  4658. @pytest.mark.parametrize('x_inverted', [False, True])
  4659. @pytest.mark.parametrize('y_inverted', [False, True])
  4660. def test_indicate_inset_inverted(x_inverted, y_inverted):
  4661. """
  4662. Test that the inset lines are correctly located with inverted data axes.
  4663. """
  4664. fig, (ax1, ax2) = plt.subplots(1, 2)
  4665. x = np.arange(10)
  4666. ax1.plot(x, x, 'o')
  4667. if x_inverted:
  4668. ax1.invert_xaxis()
  4669. if y_inverted:
  4670. ax1.invert_yaxis()
  4671. rect, bounds = ax1.indicate_inset([2, 2, 5, 4], ax2)
  4672. lower_left, upper_left, lower_right, upper_right = bounds
  4673. sign_x = -1 if x_inverted else 1
  4674. sign_y = -1 if y_inverted else 1
  4675. assert sign_x * (lower_right.xy2[0] - lower_left.xy2[0]) > 0
  4676. assert sign_x * (upper_right.xy2[0] - upper_left.xy2[0]) > 0
  4677. assert sign_y * (upper_left.xy2[1] - lower_left.xy2[1]) > 0
  4678. assert sign_y * (upper_right.xy2[1] - lower_right.xy2[1]) > 0
  4679. def test_set_position():
  4680. fig, ax = plt.subplots()
  4681. ax.set_aspect(3.)
  4682. ax.set_position([0.1, 0.1, 0.4, 0.4], which='both')
  4683. assert np.allclose(ax.get_position().width, 0.1)
  4684. ax.set_aspect(2.)
  4685. ax.set_position([0.1, 0.1, 0.4, 0.4], which='original')
  4686. assert np.allclose(ax.get_position().width, 0.15)
  4687. ax.set_aspect(3.)
  4688. ax.set_position([0.1, 0.1, 0.4, 0.4], which='active')
  4689. assert np.allclose(ax.get_position().width, 0.1)
  4690. def test_spines_properbbox_after_zoom():
  4691. fig, ax = plt.subplots()
  4692. bb = ax.spines['bottom'].get_window_extent(fig.canvas.get_renderer())
  4693. # this is what zoom calls:
  4694. ax._set_view_from_bbox((320, 320, 500, 500), 'in',
  4695. None, False, False)
  4696. bb2 = ax.spines['bottom'].get_window_extent(fig.canvas.get_renderer())
  4697. np.testing.assert_allclose(bb.get_points(), bb2.get_points(), rtol=1e-6)
  4698. def test_cartopy_backcompat():
  4699. class Dummy(matplotlib.axes.Axes):
  4700. ...
  4701. class DummySubplot(matplotlib.axes.SubplotBase, Dummy):
  4702. _axes_class = Dummy
  4703. matplotlib.axes._subplots._subplot_classes[Dummy] = DummySubplot
  4704. FactoryDummySubplot = matplotlib.axes.subplot_class_factory(Dummy)
  4705. assert DummySubplot is FactoryDummySubplot
  4706. def test_gettightbbox_ignoreNaN():
  4707. fig, ax = plt.subplots()
  4708. remove_ticks_and_titles(fig)
  4709. ax.text(np.NaN, 1, 'Boo')
  4710. renderer = fig.canvas.get_renderer()
  4711. np.testing.assert_allclose(ax.get_tightbbox(renderer).width, 496)
  4712. def test_scatter_series_non_zero_index(pd):
  4713. # create non-zero index
  4714. ids = range(10, 18)
  4715. x = pd.Series(np.random.uniform(size=8), index=ids)
  4716. y = pd.Series(np.random.uniform(size=8), index=ids)
  4717. c = pd.Series([1, 1, 1, 1, 1, 0, 0, 0], index=ids)
  4718. plt.scatter(x, y, c)
  4719. def test_scatter_empty_data():
  4720. # making sure this does not raise an exception
  4721. plt.scatter([], [])
  4722. plt.scatter([], [], s=[], c=[])
  4723. @image_comparison(['annotate_across_transforms.png'],
  4724. style='mpl20', remove_text=True)
  4725. def test_annotate_across_transforms():
  4726. x = np.linspace(0, 10, 200)
  4727. y = np.exp(-x) * np.sin(x)
  4728. fig, ax = plt.subplots(figsize=(3.39, 3))
  4729. ax.plot(x, y)
  4730. axins = ax.inset_axes([0.4, 0.5, 0.3, 0.3])
  4731. axins.set_aspect(0.2)
  4732. axins.xaxis.set_visible(False)
  4733. axins.yaxis.set_visible(False)
  4734. ax.annotate("", xy=(x[150], y[150]), xycoords=ax.transData,
  4735. xytext=(1, 0), textcoords=axins.transAxes,
  4736. arrowprops=dict(arrowstyle="->"))
  4737. @image_comparison(['secondary_xy.png'], style='mpl20')
  4738. def test_secondary_xy():
  4739. fig, axs = plt.subplots(1, 2, figsize=(10, 5), constrained_layout=True)
  4740. def invert(x):
  4741. with np.errstate(divide='ignore'):
  4742. return 1 / x
  4743. for nn, ax in enumerate(axs):
  4744. ax.plot(np.arange(2, 11), np.arange(2, 11))
  4745. if nn == 0:
  4746. secax = ax.secondary_xaxis
  4747. else:
  4748. secax = ax.secondary_yaxis
  4749. secax(0.2, functions=(invert, invert))
  4750. secax(0.4, functions=(lambda x: 2 * x, lambda x: x / 2))
  4751. secax(0.6, functions=(lambda x: x**2, lambda x: x**(1/2)))
  4752. secax(0.8)
  4753. def test_secondary_fail():
  4754. fig, ax = plt.subplots()
  4755. ax.plot(np.arange(2, 11), np.arange(2, 11))
  4756. with pytest.raises(ValueError):
  4757. ax.secondary_xaxis(0.2, functions=(lambda x: 1 / x))
  4758. with pytest.raises(ValueError):
  4759. ax.secondary_xaxis('right')
  4760. with pytest.raises(ValueError):
  4761. ax.secondary_yaxis('bottom')
  4762. def test_secondary_resize():
  4763. fig, ax = plt.subplots(figsize=(10, 5))
  4764. ax.plot(np.arange(2, 11), np.arange(2, 11))
  4765. def invert(x):
  4766. with np.errstate(divide='ignore'):
  4767. return 1 / x
  4768. ax.secondary_xaxis('top', functions=(invert, invert))
  4769. fig.canvas.draw()
  4770. fig.set_size_inches((7, 4))
  4771. assert_allclose(ax.get_position().extents, [0.125, 0.1, 0.9, 0.9])
  4772. def test_secondary_minorloc():
  4773. fig, ax = plt.subplots(figsize=(10, 5))
  4774. ax.plot(np.arange(2, 11), np.arange(2, 11))
  4775. def invert(x):
  4776. with np.errstate(divide='ignore'):
  4777. return 1 / x
  4778. secax = ax.secondary_xaxis('top', functions=(invert, invert))
  4779. assert isinstance(secax._axis.get_minor_locator(),
  4780. mticker.NullLocator)
  4781. secax.minorticks_on()
  4782. assert isinstance(secax._axis.get_minor_locator(),
  4783. mticker.AutoMinorLocator)
  4784. ax.set_xscale('log')
  4785. plt.draw()
  4786. assert isinstance(secax._axis.get_minor_locator(),
  4787. mticker.LogLocator)
  4788. ax.set_xscale('linear')
  4789. plt.draw()
  4790. assert isinstance(secax._axis.get_minor_locator(),
  4791. mticker.NullLocator)
  4792. def test_secondary_formatter():
  4793. fig, ax = plt.subplots()
  4794. ax.set_xscale("log")
  4795. secax = ax.secondary_xaxis("top")
  4796. secax.xaxis.set_major_formatter(mticker.ScalarFormatter())
  4797. fig.canvas.draw()
  4798. assert isinstance(
  4799. secax.xaxis.get_major_formatter(), mticker.ScalarFormatter)
  4800. def color_boxes(fig, axs):
  4801. """
  4802. Helper for the tests below that test the extents of various axes elements
  4803. """
  4804. fig.canvas.draw()
  4805. renderer = fig.canvas.get_renderer()
  4806. bbaxis = []
  4807. for nn, axx in enumerate([axs.xaxis, axs.yaxis]):
  4808. bb = axx.get_tightbbox(renderer)
  4809. if bb:
  4810. axisr = plt.Rectangle(
  4811. (bb.x0, bb.y0), width=bb.width, height=bb.height,
  4812. linewidth=0.7, edgecolor='y', facecolor="none", transform=None,
  4813. zorder=3)
  4814. fig.add_artist(axisr)
  4815. bbaxis += [bb]
  4816. bbspines = []
  4817. for nn, a in enumerate(['bottom', 'top', 'left', 'right']):
  4818. bb = axs.spines[a].get_window_extent(renderer)
  4819. spiner = plt.Rectangle(
  4820. (bb.x0, bb.y0), width=bb.width, height=bb.height,
  4821. linewidth=0.7, edgecolor="green", facecolor="none", transform=None,
  4822. zorder=3)
  4823. fig.add_artist(spiner)
  4824. bbspines += [bb]
  4825. bb = axs.get_window_extent()
  4826. rect2 = plt.Rectangle(
  4827. (bb.x0, bb.y0), width=bb.width, height=bb.height,
  4828. linewidth=1.5, edgecolor="magenta", facecolor="none", transform=None,
  4829. zorder=2)
  4830. fig.add_artist(rect2)
  4831. bbax = bb
  4832. bb2 = axs.get_tightbbox(renderer)
  4833. rect2 = plt.Rectangle(
  4834. (bb2.x0, bb2.y0), width=bb2.width, height=bb2.height,
  4835. linewidth=3, edgecolor="red", facecolor="none", transform=None,
  4836. zorder=1)
  4837. fig.add_artist(rect2)
  4838. bbtb = bb2
  4839. return bbaxis, bbspines, bbax, bbtb
  4840. def test_normal_axes():
  4841. with rc_context({'_internal.classic_mode': False}):
  4842. fig, ax = plt.subplots(dpi=200, figsize=(6, 6))
  4843. fig.canvas.draw()
  4844. plt.close(fig)
  4845. bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax)
  4846. # test the axis bboxes
  4847. target = [
  4848. [123.375, 75.88888888888886, 983.25, 33.0],
  4849. [85.51388888888889, 99.99999999999997, 53.375, 993.0]
  4850. ]
  4851. for nn, b in enumerate(bbaxis):
  4852. targetbb = mtransforms.Bbox.from_bounds(*target[nn])
  4853. assert_array_almost_equal(b.bounds, targetbb.bounds, decimal=2)
  4854. target = [
  4855. [150.0, 119.999, 930.0, 11.111],
  4856. [150.0, 1080.0, 930.0, 0.0],
  4857. [150.0, 119.9999, 11.111, 960.0],
  4858. [1068.8888, 119.9999, 11.111, 960.0]
  4859. ]
  4860. for nn, b in enumerate(bbspines):
  4861. targetbb = mtransforms.Bbox.from_bounds(*target[nn])
  4862. assert_array_almost_equal(b.bounds, targetbb.bounds, decimal=2)
  4863. target = [150.0, 119.99999999999997, 930.0, 960.0]
  4864. targetbb = mtransforms.Bbox.from_bounds(*target)
  4865. assert_array_almost_equal(bbax.bounds, targetbb.bounds, decimal=2)
  4866. target = [85.5138, 75.88888, 1021.11, 1017.11]
  4867. targetbb = mtransforms.Bbox.from_bounds(*target)
  4868. assert_array_almost_equal(bbtb.bounds, targetbb.bounds, decimal=2)
  4869. # test that get_position roundtrips to get_window_extent
  4870. axbb = ax.get_position().transformed(fig.transFigure).bounds
  4871. assert_array_almost_equal(axbb, ax.get_window_extent().bounds, decimal=2)
  4872. def test_nodecorator():
  4873. with rc_context({'_internal.classic_mode': False}):
  4874. fig, ax = plt.subplots(dpi=200, figsize=(6, 6))
  4875. fig.canvas.draw()
  4876. ax.set(xticklabels=[], yticklabels=[])
  4877. bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax)
  4878. # test the axis bboxes
  4879. target = [
  4880. None,
  4881. None
  4882. ]
  4883. for nn, b in enumerate(bbaxis):
  4884. assert b is None
  4885. target = [
  4886. [150.0, 119.999, 930.0, 11.111],
  4887. [150.0, 1080.0, 930.0, 0.0],
  4888. [150.0, 119.9999, 11.111, 960.0],
  4889. [1068.8888, 119.9999, 11.111, 960.0]
  4890. ]
  4891. for nn, b in enumerate(bbspines):
  4892. targetbb = mtransforms.Bbox.from_bounds(*target[nn])
  4893. assert_allclose(b.bounds, targetbb.bounds, atol=1e-2)
  4894. target = [150.0, 119.99999999999997, 930.0, 960.0]
  4895. targetbb = mtransforms.Bbox.from_bounds(*target)
  4896. assert_allclose(bbax.bounds, targetbb.bounds, atol=1e-2)
  4897. target = [150., 120., 930., 960.]
  4898. targetbb = mtransforms.Bbox.from_bounds(*target)
  4899. assert_allclose(bbtb.bounds, targetbb.bounds, atol=1e-2)
  4900. def test_displaced_spine():
  4901. with rc_context({'_internal.classic_mode': False}):
  4902. fig, ax = plt.subplots(dpi=200, figsize=(6, 6))
  4903. ax.set(xticklabels=[], yticklabels=[])
  4904. ax.spines['bottom'].set_position(('axes', -0.1))
  4905. fig.canvas.draw()
  4906. bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax)
  4907. target = [
  4908. [150., 24., 930., 11.111111],
  4909. [150.0, 1080.0, 930.0, 0.0],
  4910. [150.0, 119.9999, 11.111, 960.0],
  4911. [1068.8888, 119.9999, 11.111, 960.0]
  4912. ]
  4913. for nn, b in enumerate(bbspines):
  4914. targetbb = mtransforms.Bbox.from_bounds(*target[nn])
  4915. target = [150.0, 119.99999999999997, 930.0, 960.0]
  4916. targetbb = mtransforms.Bbox.from_bounds(*target)
  4917. assert_allclose(bbax.bounds, targetbb.bounds, atol=1e-2)
  4918. target = [150., 24., 930., 1056.]
  4919. targetbb = mtransforms.Bbox.from_bounds(*target)
  4920. assert_allclose(bbtb.bounds, targetbb.bounds, atol=1e-2)
  4921. def test_tickdirs():
  4922. """
  4923. Switch the tickdirs and make sure the bboxes switch with them
  4924. """
  4925. targets = [[[150.0, 120.0, 930.0, 11.1111],
  4926. [150.0, 120.0, 11.111, 960.0]],
  4927. [[150.0, 108.8889, 930.0, 11.111111111111114],
  4928. [138.889, 120, 11.111, 960.0]],
  4929. [[150.0, 114.44444444444441, 930.0, 11.111111111111114],
  4930. [144.44444444444446, 119.999, 11.111, 960.0]]]
  4931. for dnum, dirs in enumerate(['in', 'out', 'inout']):
  4932. with rc_context({'_internal.classic_mode': False}):
  4933. fig, ax = plt.subplots(dpi=200, figsize=(6, 6))
  4934. ax.tick_params(direction=dirs)
  4935. fig.canvas.draw()
  4936. bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax)
  4937. for nn, num in enumerate([0, 2]):
  4938. targetbb = mtransforms.Bbox.from_bounds(*targets[dnum][nn])
  4939. assert_allclose(
  4940. bbspines[num].bounds, targetbb.bounds, atol=1e-2)
  4941. def test_minor_accountedfor():
  4942. with rc_context({'_internal.classic_mode': False}):
  4943. fig, ax = plt.subplots(dpi=200, figsize=(6, 6))
  4944. fig.canvas.draw()
  4945. ax.tick_params(which='both', direction='out')
  4946. bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax)
  4947. bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax)
  4948. targets = [[150.0, 108.88888888888886, 930.0, 11.111111111111114],
  4949. [138.8889, 119.9999, 11.1111, 960.0]]
  4950. for n in range(2):
  4951. targetbb = mtransforms.Bbox.from_bounds(*targets[n])
  4952. assert_allclose(
  4953. bbspines[n * 2].bounds, targetbb.bounds, atol=1e-2)
  4954. fig, ax = plt.subplots(dpi=200, figsize=(6, 6))
  4955. fig.canvas.draw()
  4956. ax.tick_params(which='both', direction='out')
  4957. ax.minorticks_on()
  4958. ax.tick_params(axis='both', which='minor', length=30)
  4959. fig.canvas.draw()
  4960. bbaxis, bbspines, bbax, bbtb = color_boxes(fig, ax)
  4961. targets = [[150.0, 36.66666666666663, 930.0, 83.33333333333334],
  4962. [66.6667, 120.0, 83.3333, 960.0]]
  4963. for n in range(2):
  4964. targetbb = mtransforms.Bbox.from_bounds(*targets[n])
  4965. assert_allclose(
  4966. bbspines[n * 2].bounds, targetbb.bounds, atol=1e-2)
  4967. @check_figures_equal(extensions=["png"])
  4968. def test_axis_bool_arguments(fig_test, fig_ref):
  4969. # Test if False and "off" give the same
  4970. fig_test.add_subplot(211).axis(False)
  4971. fig_ref.add_subplot(211).axis("off")
  4972. # Test if True after False gives the same as "on"
  4973. ax = fig_test.add_subplot(212)
  4974. ax.axis(False)
  4975. ax.axis(True)
  4976. fig_ref.add_subplot(212).axis("on")
  4977. def test_axis_extent_arg():
  4978. fig, ax = plt.subplots()
  4979. xmin = 5
  4980. xmax = 10
  4981. ymin = 15
  4982. ymax = 20
  4983. extent = ax.axis([xmin, xmax, ymin, ymax])
  4984. # test that the docstring is correct
  4985. assert tuple(extent) == (xmin, xmax, ymin, ymax)
  4986. # test that limits were set per the docstring
  4987. assert (xmin, xmax) == ax.get_xlim()
  4988. assert (ymin, ymax) == ax.get_ylim()
  4989. def test_datetime_masked():
  4990. # make sure that all-masked data falls back to the viewlim
  4991. # set in convert.axisinfo....
  4992. x = np.array([datetime.datetime(2017, 1, n) for n in range(1, 6)])
  4993. y = np.array([1, 2, 3, 4, 5])
  4994. m = np.ma.masked_greater(y, 0)
  4995. fig, ax = plt.subplots()
  4996. ax.plot(x, m)
  4997. dt = mdates.date2num(np.datetime64('0000-12-31'))
  4998. assert ax.get_xlim() == (730120.0 + dt, 733773.0 + dt)
  4999. def test_hist_auto_bins():
  5000. _, bins, _ = plt.hist([[1, 2, 3], [3, 4, 5, 6]], bins='auto')
  5001. assert bins[0] <= 1
  5002. assert bins[-1] >= 6
  5003. def test_hist_nan_data():
  5004. fig, (ax1, ax2) = plt.subplots(2)
  5005. data = [1, 2, 3]
  5006. nan_data = data + [np.nan]
  5007. bins, edges, _ = ax1.hist(data)
  5008. with np.errstate(invalid='ignore'):
  5009. nanbins, nanedges, _ = ax2.hist(nan_data)
  5010. np.testing.assert_allclose(bins, nanbins)
  5011. np.testing.assert_allclose(edges, nanedges)
  5012. def test_hist_range_and_density():
  5013. _, bins, _ = plt.hist(np.random.rand(10), "auto",
  5014. range=(0, 1), density=True)
  5015. assert bins[0] == 0
  5016. assert bins[-1] == 1
  5017. def test_bar_errbar_zorder():
  5018. # Check that the zorder of errorbars is always greater than the bar they
  5019. # are plotted on
  5020. fig, ax = plt.subplots()
  5021. x = [1, 2, 3]
  5022. barcont = ax.bar(x=x, height=x, yerr=x, capsize=5, zorder=3)
  5023. data_line, caplines, barlinecols = barcont.errorbar.lines
  5024. for bar in barcont.patches:
  5025. for capline in caplines:
  5026. assert capline.zorder > bar.zorder
  5027. for barlinecol in barlinecols:
  5028. assert barlinecol.zorder > bar.zorder
  5029. def test_set_ticks_inverted():
  5030. fig, ax = plt.subplots()
  5031. ax.invert_xaxis()
  5032. ax.set_xticks([.3, .7])
  5033. assert ax.get_xlim() == (1, 0)
  5034. def test_aspect_nonlinear_adjustable_box():
  5035. fig = plt.figure(figsize=(10, 10)) # Square.
  5036. ax = fig.add_subplot()
  5037. ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy.
  5038. ax.set(xscale="log", xlim=(1, 10),
  5039. yscale="logit", ylim=(1/11, 1/1001),
  5040. aspect=1, adjustable="box")
  5041. ax.margins(0)
  5042. pos = fig.transFigure.transform_bbox(ax.get_position())
  5043. assert pos.height / pos.width == pytest.approx(2)
  5044. def test_aspect_nonlinear_adjustable_datalim():
  5045. fig = plt.figure(figsize=(10, 10)) # Square.
  5046. ax = fig.add_axes([.1, .1, .8, .8]) # Square.
  5047. ax.plot([.4, .6], [.4, .6]) # Set minpos to keep logit happy.
  5048. ax.set(xscale="log", xlim=(1, 100),
  5049. yscale="logit", ylim=(1 / 101, 1 / 11),
  5050. aspect=1, adjustable="datalim")
  5051. ax.margins(0)
  5052. ax.apply_aspect()
  5053. assert ax.get_xlim() == pytest.approx([1*10**(1/2), 100/10**(1/2)])
  5054. assert ax.get_ylim() == (1 / 101, 1 / 11)
  5055. def test_box_aspect():
  5056. # Test if axes with box_aspect=1 has same dimensions
  5057. # as axes with aspect equal and adjustable="box"
  5058. fig1, ax1 = plt.subplots()
  5059. axtwin = ax1.twinx()
  5060. axtwin.plot([12, 344])
  5061. ax1.set_box_aspect(1)
  5062. fig2, ax2 = plt.subplots()
  5063. ax2.margins(0)
  5064. ax2.plot([0, 2], [6, 8])
  5065. ax2.set_aspect("equal", adjustable="box")
  5066. fig1.canvas.draw()
  5067. fig2.canvas.draw()
  5068. bb1 = ax1.get_position()
  5069. bbt = axtwin.get_position()
  5070. bb2 = ax2.get_position()
  5071. assert_array_equal(bb1.extents, bb2.extents)
  5072. assert_array_equal(bbt.extents, bb2.extents)
  5073. def test_box_aspect_custom_position():
  5074. # Test if axes with custom position and box_aspect
  5075. # behaves the same independent of the order of setting those.
  5076. fig1, ax1 = plt.subplots()
  5077. ax1.set_position([0.1, 0.1, 0.9, 0.2])
  5078. fig1.canvas.draw()
  5079. ax1.set_box_aspect(1.)
  5080. fig2, ax2 = plt.subplots()
  5081. ax2.set_box_aspect(1.)
  5082. fig2.canvas.draw()
  5083. ax2.set_position([0.1, 0.1, 0.9, 0.2])
  5084. fig1.canvas.draw()
  5085. fig2.canvas.draw()
  5086. bb1 = ax1.get_position()
  5087. bb2 = ax2.get_position()
  5088. assert_array_equal(bb1.extents, bb2.extents)
  5089. def test_bbox_aspect_axes_init():
  5090. # Test that box_aspect can be given to axes init and produces
  5091. # all equal square axes.
  5092. fig, axs = plt.subplots(2, 3, subplot_kw=dict(box_aspect=1),
  5093. constrained_layout=True)
  5094. fig.canvas.draw()
  5095. renderer = fig.canvas.get_renderer()
  5096. sizes = []
  5097. for ax in axs.flat:
  5098. bb = ax.get_window_extent(renderer)
  5099. sizes.extend([bb.width, bb.height])
  5100. assert_allclose(sizes, sizes[0])
  5101. def test_redraw_in_frame():
  5102. fig, ax = plt.subplots(1, 1)
  5103. ax.plot([1, 2, 3])
  5104. fig.canvas.draw()
  5105. ax.redraw_in_frame()
  5106. def test_invisible_axes():
  5107. # invisible axes should not respond to events...
  5108. fig, ax = plt.subplots()
  5109. assert fig.canvas.inaxes((200, 200)) is not None
  5110. ax.set_visible(False)
  5111. assert fig.canvas.inaxes((200, 200)) is None
  5112. def test_xtickcolor_is_not_markercolor():
  5113. plt.rcParams['lines.markeredgecolor'] = 'white'
  5114. ax = plt.axes()
  5115. ticks = ax.xaxis.get_major_ticks()
  5116. for tick in ticks:
  5117. assert tick.tick1line.get_markeredgecolor() != 'white'
  5118. def test_ytickcolor_is_not_markercolor():
  5119. plt.rcParams['lines.markeredgecolor'] = 'white'
  5120. ax = plt.axes()
  5121. ticks = ax.yaxis.get_major_ticks()
  5122. for tick in ticks:
  5123. assert tick.tick1line.get_markeredgecolor() != 'white'
  5124. @pytest.mark.parametrize('auto', (True, False, None))
  5125. def test_unautoscaley(auto):
  5126. fig, ax = plt.subplots()
  5127. x = np.arange(100)
  5128. y = np.linspace(-.1, .1, 100)
  5129. ax.scatter(x, y)
  5130. post_auto = ax.get_autoscaley_on() if auto is None else auto
  5131. ax.set_ylim((-.5, .5), auto=auto)
  5132. assert post_auto == ax.get_autoscaley_on()
  5133. fig.canvas.draw()
  5134. assert_array_equal(ax.get_ylim(), (-.5, .5))
  5135. @pytest.mark.parametrize('auto', (True, False, None))
  5136. def test_unautoscalex(auto):
  5137. fig, ax = plt.subplots()
  5138. x = np.arange(100)
  5139. y = np.linspace(-.1, .1, 100)
  5140. ax.scatter(y, x)
  5141. post_auto = ax.get_autoscalex_on() if auto is None else auto
  5142. ax.set_xlim((-.5, .5), auto=auto)
  5143. assert post_auto == ax.get_autoscalex_on()
  5144. fig.canvas.draw()
  5145. assert_array_equal(ax.get_xlim(), (-.5, .5))
  5146. @check_figures_equal(extensions=["png"])
  5147. def test_polar_interpolation_steps_variable_r(fig_test, fig_ref):
  5148. l, = fig_test.add_subplot(projection="polar").plot([0, np.pi/2], [1, 2])
  5149. l.get_path()._interpolation_steps = 100
  5150. fig_ref.add_subplot(projection="polar").plot(
  5151. np.linspace(0, np.pi/2, 101), np.linspace(1, 2, 101))
  5152. @pytest.mark.style('default')
  5153. def test_autoscale_tiny_sticky():
  5154. fig, ax = plt.subplots()
  5155. ax.bar(0, 1e-9)
  5156. fig.canvas.draw()
  5157. assert ax.get_ylim() == (0, 1.05e-9)
  5158. @pytest.mark.parametrize('size', [size for size in mfont_manager.font_scalings
  5159. if size is not None] + [8, 10, 12])
  5160. @pytest.mark.style('default')
  5161. def test_relative_ticklabel_sizes(size):
  5162. mpl.rcParams['xtick.labelsize'] = size
  5163. mpl.rcParams['ytick.labelsize'] = size
  5164. fig, ax = plt.subplots()
  5165. fig.canvas.draw()
  5166. for name, axis in zip(['x', 'y'], [ax.xaxis, ax.yaxis]):
  5167. for tick in axis.get_major_ticks():
  5168. assert tick.label1.get_size() == axis._get_tick_label_size(name)